I have a loop where single iteration is skipped using continue
:
for(int i=0;i<5;i++){
if(i==2){
continue;
}
System.out.println(i);
}
Output would be 0 1 3 4
Based on my criteria above like i==2, I want to get output 0 1 4
. Meaning I want to skip 2 iterations. How do I do that?
for(int i=0;i<5;i++){
if(i==2){
i++
continue;
}
System.out.println(i);
}
Increment i by one inside the if statement.
I would stay away from skipping the loop for certain counters. What do you gain from it? Meaning:
for (int i=0; i < 5; i++) {
if (i != 2 && i != 3) {
// do whatever needs to be done
}
}
achieves the exact same thing; without introducing implicit "goto" logic. Why manipulating the control flow this way - without a need?
You can do this:
for (int i = 0; i < 5; i++) {
if (i == 2)
i += 2;
System.out.println(i);
}
But I agree with others that it is a bad idea to change a loop variable like this.
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.