迴圈讓相同操作重複執行。Java 提供三種基本迴圈 + 增強型 for (JDK 1.5)。
while (布林運算式) {
// 迴圈體
}
條件為 true 才進入,可能零次執行。
int x = 10;
while (x < 20) {
System.out.println("x = " + x);
x++;
}
// 輸出 10~19
do {
// 迴圈體
} while (布林運算式);
至少執行一次,再判斷條件決定是否繼續。
int x = 10;
do {
System.out.println("x = " + x);
x++;
} while (x < 20); // 同樣輸出 10~19
for (初始化; 布林運算式; 更新) {
// 迴圈體
}
執行流程:初始化 → 判斷 → 執行體 → 更新 → 判斷…
for (int x = 10; x < 20; x++) {
System.out.println("x = " + x);
}
for (int i=0, j=10; ifor (;;) 等同 while(true)for (元素型別 變數 : 陣列或 Iterable) {
// 迴圈體
}
優點: 語法簡潔,避免索引越界。限制: 僅順序讀取,無法修改陣列元素本身(基本型別修改副本),無索引可用。
int[] nums = {10, 20, 30, 40, 50};
for (int n : nums) System.out.print(n + ","); // 10,20,30,40,50,
String[] names = {"James", "Larry", "Tom"};
for (String name : names) System.out.print(name + ","); // James,Larry,Tom,
for (int x : nums) {
if (x == 30) break; // 直接結束迴圈
System.out.println(x);
}
// 輸出 10, 20
for (int x : nums) {
if (x == 30) continue; // 跳過 30
System.out.println(x);
}
// 輸出 10, 20, 40, 50
巢狀迴圈中跳出外層:
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) break outer; // 跳出雙層
System.out.println(i + "," + j);
}
}
| 迴圈類型 | 適用場景 |
|---|---|
| for | 已知迴圈次數、計數器需求 |
| while | 未知次數、前置條件判斷 |
| do-while | 至少一次、選單驅動程式 |
| foreach | 遍歷陣列/Collection、唯讀 |
foreach 底層用迭代器,陣列直接索引較快;極度熱點路徑可用傳統 for。for (int i=0; i → 先存 int n = list.size()。 continue 在 for 中執行更新運算式,在 while/do-while 直接判斷條件。break 或 return 跳出條件。