[英]skipping iteration in while loop java
我只是编程的初学者,上周刚开始在我们学校学习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
我已经使用了循环来做到这一点,它工作良好
这是我的代码:
//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()
之前递增,因此它会打印出一个加上所需的值
顺便说一句,在@GBlodgett给出的第一个答案中,您知道为什么您的程序没有显示您期望的结果。 这就是您可以实现结果的方式。
//使用while循环
int counter = 0;
while(counter < 5){
counter++;
if(counter == 3){
continue;
}
System.out.println(counter);
}
问题是一旦counter == 3,它将始终击中if语句为true,并且永远不会再递增counter。 因此,您的while循环将打印1 2,然后无限执行。
为了解决此问题,请像下面这样编码:
// Using while Loop
int counter = 1;
while(counter <= 5){
if(counter == 3){
counter++;
continue;
}
System.out.println(counter);
counter++;
}
只需在继续语句之前添加counter ++。 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.