简体   繁体   中英

Loop logic (Java)

This may seem silly, but I'm a bit confused about the following code:

public class Loops{

public static void main(String[] args) {

    int i = 0;
    int j = 2;
    int k = 0;
    boolean continue = i<j;
    while (continue && k < 2) {
        i++;
        j--;
        k++;
    }
    System.out.println(j);
}

}

This program prints 0, but I just don't understand why it doesn't print 1. The way I see it, after one loop i = j = 1 . And thus continue = false. So if anyone can explain to me the logic behind this I would greatly appreciate it!

continue does not reevaluate itself after every loop iteration because he is defined outside of the loop. instead, check in the loop condition for i < j

    while (i<j && k < 2) {
        i++;
        j--;
        k++;
    }

Your loop would be optimized by compiler as:

boolean continue = i<j;
while (true && k < 2)

and finally

while (k < 2)

So it need to loop two times to exit

After the first loop: j == 1, k == 1 
After the second loop: j == 0, k == 2, exit now

this is why finally j == 0

Try out putting condition inside a while() :

while (i<j && k < 2)

Continue is only set outside of loop body, it is never updated during the loop. Thus continue is set to true before the loop starts and then never modified again.

You only set the value of variable 'k' once and consequently continue as well. You need to re-evaluate the conditional expression inside the loop as well.

That said, I would suggest you refrain from using 'continue' as a varible name; I'm fairly certain it is a reserved word in many languages.

First of all, your continue variable always evaluates to true (0 < 2) so we can ignore it.

First iteration:

  • i ends up evaluating to 1.
  • j ends up evaluating to 1.
  • k ends up evaluating to 1.
  • As k < 2 , we do another iteration.

Second iteration:

  • i ends up evaluating to 2.
  • j ends up evaluating to 0.
  • k ends up evaluating to 2.
  • As k == 2 , we exit the loop.

Then we print j, which evaluates to 0.

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