java - 为什么我得到错误的输出?

标签 java output division

我是 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/

相关文章:

Java 输出格式——尾随零

java - (Java) 查找可被数字整除的数字并将其添加到要打印的数组的方法

c++ - 将一个整数除以一个 double

java - 在android中启动 Activity 时隐藏标题栏中的应用程序启动器图标

java - Stop() 当前正在执行的定时器

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - 在jpanel上画线

java - Java中的字符比空格小?

c - 如何在不转到下一行的情况下在 C 中使用 printf() 和 scanf()?

python - python除2/5.0为什么会报错?