Home > Software design >  Please explain this Java loop logic error
Please explain this Java loop logic error

Time:02-17

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!

CodePudding user response:

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.

CodePudding user response:

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.

  • Related