简体   繁体   中英

Java || while statement with Infinite Loop

Why does the following produce an infinite loop?

    int sum = 0;    
    int k = 1;
    while (sum < 12 || k < 4)
    sum += k;

    System.out.println(sum);

I would assume the output would be 12, once sum reaches 12 while k remains at 1.

you should use while (sum < 12 && k < 4), otherwise K < 4 will always be true and the loop will continue running.

if you use OR, the loops continue when one of those conditions are true. The conditions are for the loop to continue, not to stop.

false || true == true
true || true == true
false || false == false

false && true == false
true && true == true
false && false == false

the resulting true or false determines if the loop continues

k isn't incremented.

int sum = 0; 
int k = 1; 

while (sum < 12 || k < 4) {
    sum += k; 
     k++;
}

System.out.println(sum);

In your code k doesn't increment, so the condition remains true. So that's why your loop is infinite.

 int sum = 0;    // sum is 0
  int k = 1;       // k is 1 
   while (sum < 12 || k < 4) {
    sum += k;   // sum is incremented by 1 each time it loops
  }

System.out.println(sum);

But here your value of k is still less than 4. So it loops infinite.

EDIT: Well i'm making it a bit more clear

Here is your while loop

while (sum < 12 || k < 4)

It means either sum < 12 has to be true or k < 4 has to be true, to loop the while loop.

And here your k < 4 condition is still true. so that's why it keep looping infinite.

Your k value remains constant across all the iterations.

Your loop condition is sum<12 or k<4 . Since you are not changing the k value across iterations it will be always less than 4 and the loop keeps on going.

You use the || statement. Read any documentation about "|| &&" || => OR. If left side of statement is true and right is false = true (Using ||)

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