| 1. 控制變數初始設定 |
| 2. 迴圈結束條件測試 |
| 3. 調整控制變數的值 |
關鍵字 (keyword) do 與 while 構成 Java 中迴圈的一種,常用於後測式的迴圈,意思是迴圈會先進行第一輪,然後才進行迴圈的結束條件測試,形式如下

類似 while 陳述, do-while 下方 while 後的小括號為結束條件測試,小括號後需接分號,另外有關控制變數的初始設定及調整,這都需要放在其它地方。
下例計算 1 到 100 所有整數的和,示範 do-while 迴圈的簡單使用
class DoWhileDemo1 {
public static void main(String[] args) {
int sum = 0;
int i = 1;
do {
sum += i++;
} while (i <= 100);
System.out.println("1 + 2 + .... + 99 + 100 = " + sum);
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:DoWhileDemo1.java
功能:示範 do-while 迴圈陳述的使用
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

迴圈也可以是巢狀的 (nested) ,所謂巢狀的迴圈是指迴圈中包含其他的迴圈,由於我們利用程式碼縮排 (indentation) 的方式,使該段程式碼凹陷進去,看似巢的樣子,故稱巢狀。
下例程式印出九九乘法表,就是利用兩個 do-while 迴圈,一個 do-while 迴圈之中包含另一個 do-while 迴圈
class DoWhileDemo2 {
public static void main(String[] args) {
int i, j;
i = 1;
do {
j = 1;
do {
System.out.print((i * j) + " ");
j++;
} while (j <= 9);
i++;
System.out.println();
} while (i <= 9);
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:DoWhileDemo2.java
功能:示範 do-while 迴圈陳述的使用
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

若利用關鍵字 break 則可以挑出迴圈,利用關鍵字 continue 則會跳過迴圈這一輪的執行,下例在印出九九乘法表的程式中加入了 break 與 continue 陳述
class DoWhileDemo3 {
public static void main(String[] args) {
int i, j;
i = 1;
do {
if (i == 4) {
i++;
continue;
}
j = 1;
do {
if (j == 8) {
break;
}
System.out.print((i * j) + " ");
j++;
} while (j <= 9);
i++;
System.out.println();
} while (i <= 9);
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:DoWhileDemo3.java
功能:示範 do-while 迴圈陳述的使用
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

第 9 行使用 contiune 陳述,因此 4 乘法表的那一列不會被印出,此外,第 15 行使用 break 陳述,因此每個數只乘到 7 為止。
do-while 迴圈也可利用 for 迴圈來取代,反之亦然。
| 中英文術語對照 | |
|---|---|
| 迴圈 | loop |
| 關鍵字 | keyword |
| 運算式 | expression |
| 巢狀的 | nested |
| 縮排 | indentation |
| 陣列 | array |
參考資料
http://download.oracle.com/javase/tutorial/java/nutsandbolts/while.html
http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
http://java.sun.com/docs/books/jls/third_edition/html/statements.html
http://download.oracle.com/javase/tutorial/java/nutsandbolts/while.html
http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
http://java.sun.com/docs/books/jls/third_edition/html/statements.html
沒有留言:
張貼留言