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.

14th Sep 2016, 7:04 PM
Moji 99
Moji 99 - avatar
6 ответов
+ 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
14th Sep 2016, 7:19 PM
Zen
Zen - avatar
+ 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.
14th Sep 2016, 7:28 PM
Zen
Zen - avatar
+ 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; }
14th Sep 2016, 7:12 PM
Zen
Zen - avatar
- 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??
14th Sep 2016, 7:13 PM
Moji 99
Moji 99 - avatar
- 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.
14th Sep 2016, 7:23 PM
Moji 99
Moji 99 - avatar
- 1
Thanks man, I appreciate your kindness :)
14th Sep 2016, 7:31 PM
Moji 99
Moji 99 - avatar