int i = 0)for (初始化; 判斷條件; 控制條件) {
循環體;
}
執行順序:初始化 → 判斷 → 循環體 → 控制 → 判斷 → ...
經典範例:
// 1-100 偶數和
int sum = 0;
for (int i = 2; i <= 100; i += 2) sum += i;
// 5! 階乘
int fact = 1;
for (int i = 2; i <= 5; i++) fact *= i;
// 水仙花數 (三位數各位立方和等於自身)
for (int n = 100; n < 1000; n++) {
int g = n % 10, s = n / 10 % 10, b = n / 100;
if (g*g*g + s*s*s + b*b*b == n) System.out.println(n);
}
while (判斷條件) {
循環體;
控制條件; // 易忘,導致死循環
}
適用場景:如「紙疊幾次超過珠峰高度」——次數不可預知:
int count = 0;
int thickness = 1; // 0.01mm → 1 單位
int target = 884800; // 8848m → 884800 單位
while (thickness < target) {
thickness *= 2;
count++;
}
System.out.println("需疊 " + count + " 次"); // 輸出 27
do {
循環體;
控制條件;
} while (判斷條件);
典型用途:選單驅動程式、輸入驗證至少提示一次。
| 循環類型 | 優先級 | 適用場景 | 變數作用域 |
|---|---|---|---|
| for | 最高 | 已知範圍、計次、陣列/集合遍歷 | 循環變數僅在 for 內可見 |
| while | 次之 | 未知次數、條件驅動、讀取流直到 EOF | 變數外部可見,便於循環後使用 |
| do-while | 最低 | 至少執行一次、選單/輸入驗證 | 同 while |
// 直角三角形 *
for (int row = 1; row <= 5; row++) {
for (int col = 1; col <= row; col++) {
System.out.print("*");
}
System.out.println(); // 換行
}
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + "*" + i + "=" + (i*j) + "\t");
}
System.out.println();
}
| 關鍵字 | 作用範圍 | 效果 | 典型場景 |
|---|---|---|---|
| break | 單層循環 / switch | **完全跳出**該循環 | 找到目標提前結束搜尋 |
| continue | 單層循環 | **跳過本次**剩餘循環體,進入下一次判斷 | 跳過特定條件繼續處理 |
| return | 方法 | **結束整個方法**,返回調用處 | 驗證失敗提前返回、找到結果返回 |
outer: for (int i = 0; i < 3; i++) {
inner: for (int j = 0; j < 4; j++) {
if (j == 2) break outer; // 直接跳出 outer 標籤的循環
System.out.print("*");
}
System.out.println();
}
/*
每天存 2.5 元,每 5 天花 6 元,問幾天存滿 100 元?
*/
double daily = 2.5;
double total = 0;
int day = 1;
while (true) {
total += daily;
if (total >= 100) {
System.out.println("第 " + day + " 天存滿 100 元");
break;
}
if (day % 5 == 0) {
total -= 6;
System.out.println("第 " + day + " 天花費 6 元");
}
day++;
}
<= vs < → 邊界值測試 (0, 1, n-1, n)