2013-01-17 91 views
-1

讓我們看看下面的代碼片段。如何在while循環中繼續使用語句?

int i = 0; 
    while (i <= 10) 
    { 
     System.out.println(i); 
     if (i == 8) 
     { 
      continue; 
     } 
     i++; 
    } 

爲了避免無限循環,我必須做些什麼改變?謝謝。

+1

'我++; if(i == 9){continue;}'? – assylias

+7

你的問題完全令人困惑。是的,當你繼續時,它會回到循環的頂部 - 包括檢查條件。如果你不想要這種行爲,不要使用'繼續'......你真的想達到什麼目的? –

+2

這基本上是用'while'寫一個'for'循環,然後有意地打破控制變量的特定條件。通常,您會使用continue來跳過針對特定條件的處理,而不是跳過遞增控制變量 – Gus

回答

7

一開始,而不是做你的增量底:

int i = -1; 
while (i <= 10) 
{ 
    i++; 
    System.out.println(i); 
    if (i == 8) 
    { 
     continue; 
    } 

    // Presumably there would be some code here, or this doesn't really make much sense 
} 

,或者取決於語言,你可以這樣做是正確的while聲明(記住運算符優先級保持在你是否選擇i++++i

int i = 0 
while (i++ <= 10) 
{ 
    System.out.println(i); 
    if (i == 8) 
    { 
     continue; 
    } 

    // Presumably there would be some code here, or this doesn't really make much sense 
} 

我會質疑這種結構,即使使用while循環。如果要在循環中使用計數器,則for循環通常更合適。

+0

這是什麼符合我的要求。感謝你的回答。 –

1

代替的quickfix溶液,讓我們看看您的代碼爲一分鐘,並通過它逐行步驟:

int i = 0; 
while (i <= 10) 
{ 
    System.out.println(i); 
    if (i == 8) 
    { 
     continue; 
    } 
    i++; 
} 

i首先是0,其小於10,因此其進入循環,打印0並且增量爲1.然後i變成2,3,4 ...... 8

當它變成等於8而不是遞增時,它彈回到循環的開始,再次打印8 ..檢查價值i(這是8),並繼續,印8 ..它會一直這樣做,直到永恆。

因此,在測試之前增加數量,它將按預期工作。

更改您的代碼是這樣的

int i = 0; 
while (i <= 10) 
{ 
    if (i != 8) 
    { 
     System.out.println(i); 
    } 
    i++; 
} 
+0

感謝您的解決方案。 –

0

我喜歡埃裏克Petroelje的答案。 我建議做這樣的事情:

if (++i >= 8) continue; 

另外,這幾天編譯器不夠好,要提醒你這是一個可以無限循環。還有代碼分析工具也會爲您檢測。

0

雖然這不是代碼,我會永遠建議在大多數情況下使用,它確實達到目的:

int i = 0; 
while (i <= 10) 
{ 
    Console.WriteLine(i.ToString()); 
    if (i == 8) 
    { 
    // Do some work here, then bail on this iteration. 
    goto Continue; 
    } 

Continue: // Yes, C# does support labels, using sparingly! 
    i++; 
}