2013-03-23 36 views
2

我有一個簡單的問題。爲什麼這個循環的結果是12?我認爲這將是11 ...JAVA,循環的怪異結果

public static void main(String[] args) { 
    int i = 10; 

    while (i++ <= 10){ 
    } 

    System.out.println(i); 
} 


//RESULT: 12 

回答

7

它將運行在while循環的條件兩次,第一次當i = 10,那麼它將它遞增到11。然後它會如果i <= 10再次檢查,並將是錯誤的,但它仍然會增加i,導致它變爲12.

2

發生這種情況是因爲在退出循環之前必須執行另一次檢查。

i is 10 
check i++<=10? 
i is 11 
check i++<10? 
exit 
i is 12 
1

i++說: 「給我的i當前值,然後增量它」。在這種情況下,當i = 10增加到11那麼該表達式對於以前的值10爲真,因此循環重複,i = 11測試,i增加到12,並且表達式現在爲假,停止循環。

這種增量後行爲有點令人困惑,因此只能在您需要的時候使用。在一般情況下,更好的做法是假裝++不返回任何東西,這通常會讓你的代碼的意圖更加明確:

while(i <= 10) { 
    i++; 
} 
1
Iteration 1 : i=10 
condition true ===>>> while loop executed once 
i incremented to 11 


iteration 2 : i=11 
condition false ===>>> while loop exited 
but after exiting the while loop 
i is incremented again to ===>>> i =12 

and that is what you get as output