在while循环Java中跳过迭代

时间:2018-09-24 22:34:54

标签: 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

我已经使用for循环来做到这一点,并且效果很好

这是我的代码:

//using for loop
for(int counter = 1; counter <= 5; counter++){
     if(counter == 3){
          continue;
     }
     System.out.println(counter);
}

这将打印正确的输出...

现在,任何人都可以告诉我在使用while循环进行此练习时我有什么错误吗?谢谢...

3 个答案:

答案 0 :(得分:2)

[ ... ] Integer: 123�~c, Bool: true, Float: 3.1415

此处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++; } 语句之前一样,但是continue仍会被忽略,从而导致打印3的无限循环。

counter++;

已到达int counter= 1; while(counter <= 5){ counter++; if(counter == 3){ continue; } System.out.println(counter); } ,但是它将在counter++之前递增,因此它会打印出一个加上所需的值

答案 1 :(得分:1)

顺便说一句,在@GBlodgett给出的第一个答案中,您知道为什么您的程序没有显示您期望的结果。 这是您达到目标的方式。

//使用while循环

int counter = 0;

while(counter < 5){
    counter++;
    if(counter == 3){
        continue;
    }


    System.out.println(counter);

    }

答案 2 :(得分:1)

问题在于,一旦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++;
}

只需在您的Continue语句之前添加counter ++。希望这会有所帮助。