簡體   English   中英

在while循環Java中跳過迭代

[英]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++; 語句,因此它始終為3while循環永不終止

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM