我只是编程初学者,上周我刚刚开始在我们学校学习 java。我想做的是在 java 中的 while 循环中使用 continue 语句来跳过迭代,不幸的是输出不是我所期望的......
这是我的代码:
// Using while Loop
int counter = 1;
while(counter <= 5){
if(counter == 3){
continue;
}
System.out.println(counter);
counter++;
}
输出为: 1 2 它没有打印 4 和 5,但我注意到该程序仍未终止。
我什至尝试过这样编码:
int counter = 1;
while(counter <= 5){
System.out.println(counter);
if(counter == 3){
continue;
}
counter++;
}
它只是不间断地打印 3
int counter= 1;
while(counter <= 5){
counter++;
if(counter == 3){
continue;
}
System.out.println(counter);
}
这个打印 2 4 5 6 而不是 1 2 4 5
我已经使用for循环来做到这一点并且效果很好
这是我的代码:
//using for loop
for(int counter = 1; counter <= 5; counter++){
if(counter == 3){
continue;
}
System.out.println(counter);
}
这会打印正确的输出...
现在,谁能告诉我在做这个练习时使用 while 循环的错误是什么?谢谢...
最佳答案
if(counter == 3){
continue;
}
System.out.println(counter);
counter++;
这里的continue
语句跳过了ctr++;
语句,所以它总是3
和while
循环永不终止
int counter = 1;
while(counter <= 5){
System.out.println(counter);
if(counter == 3){
continue;
}
counter++;
}
这里会到达 print 语句,因为它在 continue
语句之前,但是 counter++;
仍然会被绕过,导致打印无限循环3.
int counter= 1;
while(counter <= 5){
counter++;
if(counter == 3){
continue;
}
System.out.println(counter);
}
这里达到了 counter++
,但它会在 println()
之前递增,因此它会打印出您想要的值加一
关于java - java中的while循环跳过迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52488233/