我是 Java 的新手,正在尝试编写一个简单的代码。这是描述: 编写一个程序,提示用户输入数字 X。打印 从 1 到 X 的数字。然而,代替 4 的倍数打印“qqqq”。代替 7 的倍数,打印“七”。如果一个数能同时被 4 和 7 整除,打印“qqqqseven”。这意味着如果我输入 4,我的输出应该是 1, 2, 3, (qqqq), ...但是我得到 1(qqqq), 2(qqqq), 3(qqqq), 4(qqqq).... . 谁能帮助我,让我知道我哪里做错了?任何帮助表示赞赏。比你。
public static void main(String args[])
{
//Print Method
System.out.println("Enter number upto which you want to print: ");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
for(int i=1; i <= x; i++)
{
System.out.println(i);
//if x is multiples of 4
if (x % 4 == 0)
System.out.println("qqqq");
//if x is multiples of 7
if (x % 7 == 0)
System.out.println("seven");
//if x is divisible by 4 and 7
if (x % 4 == 0 && x % 7 == 0)
System.out.println("qqqqseven");
}
}
最佳答案
替换
if (x % 4 == 0)
与
if (i % 4 == 0)
对其他出现的 % 做同样的事情
要获得 28 的倍数的正确输出,您需要将代码修改为:
if (i % 4 == 0 && i % 7 == 0) { // if i is a multiple of 28 (of both 4 & 7)
System.out.println("qqqqseven");
}
else {
if (i % 4 == 0) { // if i is multiples of 4
System.out.println("qqqq");
}
else if (i % 7 == 0) { // if i is multiples of 7
System.out.println("seven");
}
}
关于java - 为什么我得到错误的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30532133/