Reputation: 7298
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);
}
}
}
}
}
Upvotes: 0
Views: 590
Reputation: 2009
for (i = 1; i <= 30; i++) {
if (i % 2 != 0) {
if(i % 7 != 0) {
if(i % 9 != 0)
System.out.println(i);
}
}
}
Upvotes: 0
Reputation: 22172
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.
Upvotes: 3
Reputation: 1533
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);
}
}
}
}
Upvotes: 1
Reputation: 16035
You need to use AND instead of OR in your comparison. In the comparison i % 7 != 0 || i % 9 != 0
, even if i mod 7 is 0, i mod 9 may not be and vice versa.
Upvotes: 2