do-while 是 Java 三大迴圈結構之一,核心特徵是先執行迴圈體,再判斷條件,保證至少執行一次。這特性適用於選單驅動程式、輸入驗證、至少一次業務邏輯等場景。本文系統性解析語法、流程、陷阱與 while/for 對比。
do {
// 迴圈體 (至少執行一次)
statement(s);
} while (boolean_expression); // 注意結尾分號!
┌─────────────┐
│ 進入 do │
└──────┬──────┘
▼
┌─────────────┐
│ 執行迴圈體 │ ← 無條件執行第一次
└──────┬──────┘
▼
┌─────────────┐
│ 條件判斷 │ ← true 回迴圈體,false 跳出
│ (boolean) │
└──────┬──────┘
┌────┴────┐
true false
│ │
▼ ▼
┌─────────┐ 結束迴圈
│ 繼續執行 │
└────┬────┘
│
└──────────┘ (回到條件判斷)
public class DoWhileSum {
public static void main(String[] args) {
int i = 1;
int sum = 0;
do {
sum += i;
i++;
} while (i <= 100);
System.out.println("1+2+...+100 = " + sum); // 5050
}
}
public class DoWhileAtLeastOnce {
public static void main(String[] args) {
int j = 5; // 初始值已不符合條件 j < 3
do {
System.out.println("執行了!j = " + j); // 仍會執行一次
j++;
} while (j < 3);
// 輸出:執行了!j = 5
}
}
對比:while (j < 3) 條件前置,零次執行;do-while 條件後置,一次執行。
import java.util.Scanner;
public class MenuDrivenApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\n=== 學生管理系統 ===");
System.out.println("1. 新增學生");
System.out.println("2. 查詢學生");
System.out.println("3. 刪除學生");
System.out.println("0. 離開系統");
System.out.print("請選擇: ");
choice = scanner.nextInt();
switch (choice) {
case 1: System.out.println("→ 執行新增邏輯"); break;
case 2: System.out.println("→ 執行查詢邏輯"); break;
case 3: System.out.println("→ 執行刪除邏輯"); break;
case 0: System.out.println("→ 感謝使用,再見!"); break;
default: System.out.println("→ 選項無效,請重新輸入");
}
} while (choice != 0);
scanner.close();
}
}
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int age;
do {
System.out.print("請輸入年齡 (1-120): ");
while (!scanner.hasNextInt()) {
System.out.print("格式錯誤,請輸入數字: ");
scanner.next(); // 清除無效輸入
}
age = scanner.nextInt();
if (age < 1 || age > 120) {
System.out.println("範圍錯誤!");
}
} while (age < 1 || age > 120);
System.out.println("錄入成功:年齡 = " + age);
scanner.close();
}
}
| 特性 | while | do-while | for |
|---|---|---|---|
| 條件檢查時機 | 前置 (Pre-test) | 後置 (Post-test) | 前置 (Pre-test) |
| 最少執行次數 | 0 | 1 | 0 |
| 適用場景 | 未知次數、條件複雜 | 選單、輸入驗證、至少一次 | 已知次數、計數器控制 |
| 變數作用域 | 外部宣告 | 外部宣告 | 可在初始化區宣告 (區域) |
| 語法靈活度 | 高 | 中 | 高 (增強 for、多計數器) |
| break/continue | 支援 | 支援 | 支援 |
int i = 1;
do {
int j = 1;
do {
System.out.print("*");
j++;
} while (j <= 5);
System.out.println();
i++;
} while (i <= 3);
int x = 0;
do {
x++;
if (x == 3) continue; // 跳過本次剩餘,直接判斷條件
if (x == 7) break; // 直接跳出迴圈
System.out.println(x);
} while (x < 10);
// ❌ 編譯錯誤
do {
System.out.println("test");
} while (true) // 缺少分號
// ✅ 正確
do {
System.out.println("test");
} while (true);
do {
// 業務邏輯
if (exitCondition) break;
} while (true); // 或 while (1 == 1)
for 迴圈變數作用域最小,有利於暫存器分配與逃逸分析掌握三大迴圈的語意差異與適用邊界,能寫出更符合業務邏輯、更易維護的程式碼。