简体   繁体   English

Java前循环错误

[英]Java For-Loop Error

I'm trying to print out all odd numbers that aren't multiples of 7 or 9. It works by seeing if the remainder is first not 0 when divided by two, giving the odd numbers. 我正在尝试打印不是7或9的倍数的所有奇数。它的工作原理是查看余数除以2后是否首先不是0,从而给出奇数。

But when I've put it to show the numbers if they are not multiples of 7 it just displays ALL the odd numbers, have I made a mistake? 但是,当我将其显示为不是7的倍数的数字时,它仅显示所有奇数,我犯了一个错误吗?

public class NoMultiples7and9 {

    public static void main(String[] args) {

        for (int i = 1; i <= 30; i++) {

            if (i % 2 != 0) {

                if (i % 7 != 0 || i % 9 != 0) {

                    System.out.println(i);
                }
            }
        }
    }
}

Change your code with: 使用以下方法更改代码:

for (int i = 1; i <= 30; i = i + 2) {
   if (i % 7 != 0 && i % 9 != 0) {
      System.out.println(i);
   }
}

Please note the use of the && (AND) instead of the || 请注意使用&& (AND)代替|| (OR) and the useless of the i % 2 because you can loop only on the odd numbers by changing a little bit the for loop. (OR)和无用的i % 2因为您可以通过稍微更改for循环来仅对奇数for循环。

You need to use AND instead of OR in your comparison. 在比较中,您需要使用AND而不是OR。 In the comparison i % 7 != 0 || i % 9 != 0 在比较中i % 7 != 0 || i % 9 != 0 i % 7 != 0 || i % 9 != 0 , even if i mod 7 is 0, i mod 9 may not be and vice versa. i % 7 != 0 || i % 9 != 0 ,即使i mod 7为0,i mod 9也可能不是,反之亦然。

your inner if statement is wrong, it will cause all odd numbers that aren't divisible by by both 7 and 9 to be printed. 您的内部if语句错误,这将导致所有不能被7和9整除的奇数被打印出来。 I bet if you change your loop to go to 63 it won't print 63. The initial % 2 check is also not needed. 我敢打赌,如果将循环更改为63,则不会打印63。也不需要初始%2检查。

public class NoMultiples7and9 {

    public static void main(String[] args) {

        for (int i = 1; i <= 30; i++) {

            if (i % 7 != 0 && i % 9 != 0) {

                System.out.println(i);

            }
        }
    }
}
for (i = 1; i <= 30; i++) {  
        if (i % 2 != 0) {
            if(i % 7 != 0) {
                if(i % 9 != 0)
                    System.out.println(i);
            }

        }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM