1

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!

maloomeister
  • 2,461
  • 1
  • 12
  • 21
Lax
  • 21
  • 1

2 Answers2

0

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.

  • This won't make any difference in this case. It still wouldn't display anything since the loop condition will fall true before the `if` condition. The loop would end **before** the `if` statement even comes int play in either case. Bottom line...the `if` block shouldn't even be in the loop, just display the goodies **after** (outside) the loop: `System.out.println("Cookies = " + cookies + " | Value = " + cookies / 12);` – DevilsHnd - 退職した Feb 16 '22 at 13:17
  • Thank you both, DevilsHnd was correct in that there was no need for the if statement, all I needed to do was print out the desired value. – Lax Feb 16 '22 at 18:04
0

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.