简体   繁体   中英

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.

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?

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 || (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.

You need to use AND instead of OR in your comparison. In the comparison 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.

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. I bet if you change your loop to go to 63 it won't print 63. The initial % 2 check is also not needed.

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);
            }

        }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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