2011-12-29 64 views
1

爲什麼下面的代碼執行六次?請幫助我理解這是如何運作的,因爲我試圖在沒有成功的情況下讓它進入我的腦海。Java - 做循環幫助解釋所需

我認爲這將首先執行代碼一次,則增大計數,執行它一個秒時間,增加計數,執行它一個第三時間,增加計數,執行它一個第四時間,增加計數,執行它一個第五時間,增加計數到5,然後停止。這意味着它將執行循環五個次(第一次,然後當計數是1,2,3,4)。

int count = 0; 

    do { 

     System.out.println("Welcome to Java!"); 

    } while (count++ < 5); 

回答

2

您是否嘗試過運行this code

int count = 0; 

do { 

    System.out.println("Welcome to Java! " + count); 

} while (count++ < 5); 

輸出:

Welcome to Java! 0 
Welcome to Java! 1 
Welcome to Java! 2 
Welcome to Java! 3 
Welcome to Java! 4 
Welcome to Java! 5 

這會幫助你明白髮生了什麼。其他人是否說過你的困惑最有可能在後增量操作員的工作方式上。

爲了幫助您瞭解前置和後置遞增操作符讓我們運行another code sample

int a = 0; 
int b = 0; 
System.out.println("pre increment "+ ++a); 
System.out.println("post increment "+ b++); 

輸出:

pre increment 1 
post increment 0 

總結:帶後增量的表達式求值之前變量遞增,在預增加之後,表達式被評估爲之後變量e遞增。

1

其後綴運算所以整個表達式的第一評價;然後增加

控制將流這樣

0 
Welcome to Java! 
//condition check : 0 then 1 
Welcome to Java! 
//condition check : 1 then 2 
Welcome to Java! 
//condition check : 2 then 3 
Welcome to Java! 
//condition check : 3 then 4 
Welcome to Java! 
//condition check : 4 then 5 
Welcome to Java! 
//condition check : 5 then 6 
+0

比較完成後執行'count ++'。 – ZeissS 2011-12-29 17:18:57

0
count++; // <-- would execute the above code 6 times 

是後增量和

++count; // <-- would execute the above code 5 times 

是預增量

考慮:

while (count++ < 5) System.out.println(count); // prints 1 2 3 4 5 
while (++count < 5) System.out.println(count); // prints 1 2 3 4 

所以你do...while第一執行沒有一個比較(因爲做的),然後運行比較。

如果是預遞增它可以被重新寫成這樣:

int count = 0; 
do { 
    // print 
    count = count + 1; 
} while (count < 5) 

如果是後遞增它可以被重新寫成這樣:那是因爲你使用

int count = 0; 
while (count < 5) { 
    // print statement 
    count = count + 1; 
} 
1

後遞增。首先對while條件進行評估(的值爲之前爲的增量),然後count遞增。

嘗試++count(首先增加然後返回值)。

編輯:

注意的是,雖然使用它在

for(int i = 0; i < n; i++) {} 

是確定的(它通常會得到優化,等等),

for(int i = 0; i < n; ++i) {} 

是從更好一點語義角度來看IMO。

在運算符重載的語言中,它變得更加複雜,其中i ++可能與++ i有不同的副作用。