Java while 迴圈
while 迴圈會在條件為 true 時持續執行,適合不確定執行次數的情況。
基本語法
while (條件) {
// 迴圈主體
}
基本範例
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
// 1, 2, 3, 4, 5
執行流程
- 檢查條件
- 如果條件為 true,執行迴圈主體
- 回到步驟 1
- 如果條件為 false,結束迴圈
while vs for
// for 迴圈:已知執行次數
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// while 迴圈:條件控制
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
實際應用
讀取使用者輸入
Scanner scanner = new Scanner(System.in);
String input = "";
while (!input.equals("quit")) {
System.out.print("請輸入指令(輸入 quit 離開):");
input = scanner.nextLine();
System.out.println("你輸入了:" + input);
}
計算數字位數
int number = 12345;
int digits = 0;
while (number > 0) {
digits++;
number /= 10;
}
System.out.println("位數:" + digits); // 5
猜數字遊戲
Random random = new Random();
int answer = random.nextInt(100) + 1; // 1-100
Scanner scanner = new Scanner(System.in);
int guess = 0;
int attempts = 0;
while (guess != answer) {
System.out.print("猜一個 1-100 的數字:");
guess = scanner.nextInt();
attempts++;
if (guess < answer) {
System.out.println("太小了!");
} else if (guess > answer) {
System.out.println("太大了!");
}
}
System.out.println("恭喜!答案是 " + answer);
System.out.println("你猜了 " + attempts + " 次");
驗證輸入
Scanner scanner = new Scanner(System.in);
int age = -1;
while (age < 0 || age > 150) {
System.out.print("請輸入年齡 (0-150):");
if (scanner.hasNextInt()) {
age = scanner.nextInt();
} else {
scanner.next(); // 清除錯誤輸入
}
}
System.out.println("你的年齡是:" + age);
計算最大公因數 (GCD)
int a = 48, b = 18;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
System.out.println("GCD = " + a); // 6
無限迴圈
// 無限迴圈
while (true) {
// 需要使用 break 跳出
if (condition) {
break;
}
}
do-while 迴圈
do-while 迴圈至少會執行一次:
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
詳細說明請參考 Java do while 迴圈。
break 和 continue
int i = 0;
while (i < 10) {
i++;
if (i == 3) continue; // 跳過 3
if (i == 8) break; // 在 8 停止
System.out.println(i);
}
// 1, 2, 4, 5, 6, 7
常見錯誤
忘記更新條件變數
int i = 0;
while (i < 5) {
System.out.println(i);
// 忘記 i++,造成無限迴圈!
}
條件永遠為 true
int x = 10;
while (x > 0) {
System.out.println(x);
x++; // 應該是 x--
}
while vs for 使用時機
| 情況 | 建議使用 |
|---|---|
| 已知執行次數 | for |
| 遍歷陣列/集合 | for / for-each |
| 條件控制 | while |
| 讀取輸入直到特定值 | while |
| 至少執行一次 | do-while |