0
I can't understand how continue works.
Why doesn't this code outputs : 0 1 2 4 5 ?? int x = 0; while(x < 6){ if(x == 3){ continue; } System.out.println(x); x++; } Please tell me about it with your own examples.
6 Answers
+ 2
Continue skips the rest of the current loop and continue with the next.
for (int i = 0; i < 10; i++) {
if (i %2 == 0) {
//skipping when i is even
continue;
}
System.out.print(i);
}
//prints 13579
+ 2
You can use continue in while loops, you just have to make sure that the loop variable is correctly adjusted before continuing. You don't need to think about it with for loops, which is always nice.
+ 1
The problem is that once x reaches 3, it is not incremented anymore and we enter an infinite loop. You wouldn't have this problem if you were using a for loop.
This is what you should put:
if(x == 3){
x++;
continue;
}
- 1
Hmm I see Zen, but I just didn't understand continue in loop statements, could you please write another example with a loop so that I can fully understand the usage of continue??
- 1
Thank you so much Zen, that's much more clear right now. But just one more question: Is continue often used with for loop? As I see, there is no point in using it with other loops, which I did and it caused a bit of confusion in my mind.
- 1
Thanks man, I appreciate your kindness :)