在學習 do/while 語句之前,先清楚 while 語句是如何工作的。while 語句是先進行條件判斷,再執行大括號內的循環體。
do/while 語句與 while 語句不同的是,它先執行大括號內的循環體,再判斷條件,如果條件不滿足,下次不在執行循環體。也就是說,在判斷條件之前,就已經執行大括號內的循環體。
示例:計算1+2+3+4......+100的結果。
1
2
3
4
5
6
7
8
9
|
public class control5{ public static void main(String[] args){ int a= 1 ,result= 0 ; do { result+=a++; } while (a<= 100 ); System.out.println(result); } } |
do-while聲明時,至少一次會循環一次,。
它的語法如下:
1
2
3
|
do { statement (s) } while (booleanexpression); |
簡單實例
1
2
3
4
5
6
7
8
9
|
public class mainclass { public static void main(string[] args) { int i = 0 ; do { system.out.println(i); i++; } while (i < 3 ); } } |
以下do-while表明至少做塊的代碼會被執行,即使一次的初始值,用于測試的表達[j]. . < 3計算錯誤的。
1
2
3
4
5
6
7
8
9
|
public class mainclass { public static void main(string[] args) { int j = 4 ; do { system.out.println(j); j++; } while (j < 3 ); } } |
利用do while來求和
1
2
3
4
5
6
7
8
9
10
11
12
|
public class mainclass { public static void main(string[] args) { int limit = 20 ; int sum = 0 ; int i = 1 ; do { sum += i; i++; } while (i <= limit); system.out.println( "sum = " + sum); } } |
總結一下三種循環的區別:
1.while循環先判斷->決定是否執行循環
2.do-while是先執行循環->判斷是否->再繼續看是否
3.for循環:先執行初始化循環;然后執行判斷,先調用,后執行循環體的內容,將變量值打印出來;然后再才執行參數修改的部分。就是先判斷再執行。