Java do-while 迴圈
do-while 迴圈會先執行一次,再檢查條件,確保迴圈至少執行一次。
基本語法
do {
// 迴圈主體
} while (條件);
注意:結尾要加分號 ;
基本範例
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
// 1, 2, 3, 4, 5
while vs do-while
關鍵差異:do-while 至少執行一次。
int x = 10;
// while:條件一開始就是 false,不會執行
while (x < 5) {
System.out.println("while: " + x);
}
// do-while:至少執行一次
do {
System.out.println("do-while: " + x);
} while (x < 5);
// 輸出:do-while: 10
實際應用
選單系統
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 scanner = new Scanner(System.in);
int age;
do {
System.out.print("請輸入年齡 (1-150):");
age = scanner.nextInt();
if (age < 1 || age > 150) {
System.out.println("輸入無效,請重新輸入");
}
} while (age < 1 || age > 150);
System.out.println("你的年齡是:" + age);
確認操作
Scanner scanner = new Scanner(System.in);
String confirm;
System.out.println("即將刪除所有資料...");
do {
System.out.print("確定要繼續嗎?(yes/no):");
confirm = scanner.nextLine().toLowerCase();
} while (!confirm.equals("yes") && !confirm.equals("no"));
if (confirm.equals("yes")) {
System.out.println("資料已刪除");
} else {
System.out.println("操作已取消");
}
密碼驗證
Scanner scanner = new Scanner(System.in);
String password;
String correctPassword = "secret123";
int attempts = 0;
int maxAttempts = 3;
do {
System.out.print("請輸入密碼:");
password = scanner.nextLine();
attempts++;
if (!password.equals(correctPassword)) {
System.out.println("密碼錯誤!剩餘 " + (maxAttempts - attempts) + " 次機會");
}
} while (!password.equals(correctPassword) && attempts < maxAttempts);
if (password.equals(correctPassword)) {
System.out.println("登入成功!");
} else {
System.out.println("已超過嘗試次數,帳號已鎖定");
}
產生隨機數直到特定條件
Random random = new Random();
int number;
do {
number = random.nextInt(100) + 1;
System.out.println("產生:" + number);
} while (number != 50); // 直到產生 50
System.out.println("找到 50 了!");
巢狀 do-while
int row = 1;
do {
int col = 1;
do {
System.out.print("* ");
col++;
} while (col <= row);
System.out.println();
row++;
} while (row <= 5);
// *
// * *
// * * *
// * * * *
// * * * * *
何時使用 do-while
| 情況 | 建議使用 |
|---|---|
| 需要先執行再判斷 | do-while |
| 選單系統 | do-while |
| 輸入驗證(至少詢問一次) | do-while |
| 一般迴圈 | while 或 for |
注意事項
不要忘記結尾的分號:
do {
// 程式碼
} while (condition); // 分號不能忘!