[英]How to skip 2 iteration in java loop
I have a loop where single iteration is skipped using continue
:我有一个循环,其中使用continue
跳过单次迭代:
for(int i=0;i<5;i++){
if(i==2){
continue;
}
System.out.println(i);
}
Output would be 0 1 3 4
输出将是0 1 3 4
Based on my criteria above like i==2, I want to get output 0 1 4
.根据我上面的标准,如 i==2,我想获得输出0 1 4
。 Meaning I want to skip 2 iterations.意思是我想跳过 2 次迭代。 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.在 if 语句中将 i 加一。
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.但是我同意其他人的观点,即像这样更改循环变量是一个坏主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.