2014-09-27 108 views
-1

有人能在這裏解釋這些代碼背後的直覺的使用:「繼續」

class ContDemo { 
    public static void main(String args[]) { 
     int i; 
     // print even numbers between 0 and 100 
     for (i = 0; i<=100; i++) { 
      if ((i%2) != 0) continue; // iterate 
      System.out.println(i); 
     } 
    } 
} 

我真不明白它背後的邏輯。有人請幫助我嗎?

+3

你不瞭解什麼? – 2014-09-27 18:41:53

+0

你想要偶數;因此,如果他們可以被2整除,你就可以展示他們。要做到這一點,你需要模塊。正如伊蘭指出的那樣,這個設計甚至沒有使用'繼續'的任何一點。繼續只跳過循環的其餘部分並進行下一次迭代。 – 2014-09-27 18:57:02

回答

1

在這個具體的例子,沒有太多點使用continue,因爲你可以簡單地將其替換爲:

for (i = 0; i<=100; i++) { 
    if ((i%2) == 0) 
     System.out.println(i); 
} 
+1

或甚至更好地刪除「if」並更改i ++與i + = 2 – 2014-09-27 19:06:36

0

的繼續關鍵字在FFG代碼的目的:

class ContDemo { 
    public static void main(String args[]) { 
    int i; 
    // print even numbers between 0 and 100 
    for(i = 0; i<=100; i++) { 
     if((i%2) != 0) continue; // iterate 
     System.out.println(i); 
    } 
    } 
} 

沒有必要,但沒有標籤的目的是處理循環所處理的條件。如for循環剛使用時,繼續關鍵字(在執行時會重新 - 執行條件,並開始從條件執行語句

例子:在FFG代碼

for(int c = 0; c < 10; c++){ 
    continue; 
    int a = 1; 
} 

continue聲明會導致。於條件不斷執行過程中(計數器加),並且當它到達10循環將結束。

int a = 1;// will never be executed.It will seen as an unreachable statement by the compiler. 

continue不同於break爲中斷ķ eyword當它執行時立即結束循環

原諒我的語法,如果有任何錯誤。我歡迎編輯。希望這可以幫助。

+0

這裏有一個小錯誤:在Java中,在關鍵字(例如continue或break)之後,不能有無法訪問的代碼。這是一個錯誤,並且由編譯器報告。因此,繼續**之後的'int a = 1;'是**錯誤。 – NoDataFound 2014-09-27 19:02:10

+0

我相信,如果使用語句,它不會返回錯誤。 – rert588 2014-09-27 19:04:28

+0

易於測試:http://pastebin.com/bnQu0j9H(jdk8) – NoDataFound 2014-09-27 19:06:27

0

「continue」跳回到循環的開始處(但不重新啓動循環...) 「break」立即退出循環。

1

正如問題的標題所說,「使用Continue ..」,所以這裏是一個解釋。每當我們需要繼續一個循環,不執行下面的

continue; 

語句中的語句 聲明,

continue; 

使用。例如,看看下面的代碼:

for (i = 0; i<=10; i++) { 
     System.out.printf(" "+i); 
     if (i>4) 
      continue; 
     System.out.println(" is less than 5"); 
    } 

輸出:

0 is less than 5 
1 is less than 5 
2 is less than 5 
3 is less than 5 
4 is less than 5 
5 6 7 8 9 10 

每當如果(ⅰ> 4)被執行塊,低於

continue; 

的發言聲明不執行。