| 1. 控制變數初始設定 |
| 2. 迴圈結束條件測試 |
| 3. 調整控制變數的值 |
關鍵字 (keyword) while 構成 Java 中迴圈的一種,常用於沒有確定重複次數的迴圈,同時 while 後面接著小括弧為迴圈結束的條件 (condition) 測試,通常為運算式 (expression) ,即為迴圈開始前進行迴圈結束條件的測試,形式如下

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

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

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

第 9 行使用 contiune 陳述,因此 4 乘法表的那一列不會被印出,此外,第 15 行使用 break 陳述,因此每個數只乘到 7 為止。
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
沒有留言:
張貼留言