'Please explain this Java loop logic error
I am expecting the below loop logic to bring cookies to 504 before printing 42. The program will run but nothing is returned.
public static void main(String[] args) {
int cookies = 500;
while(cookies % 12 != 0) {
if (cookies % 12 == 0) {
System.out.println(cookies/12);
}
cookies++;
}
}
Thank you!
Solution 1:[1]
You could switch this to a do/while to make it work. It will check the if statement first, increment your variable, then check the condition.
Solution 2:[2]
Condition 'cookies % 12 == 0' is always 'false' !
So it never prints anything!
This code will print out 42:
int cookies = 500;
while (cookies % 12 != 0) {
cookies++;
if (cookies % 12 == 0) {
System.out.println(cookies/12);
}
}
Reason: if you put the cookies++ at the end, then whenever cookies % 12 == 0, it breaks the while loop immediately, so it won't print anything.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shawn Kilger |
| Solution 2 |
