打印 1-10 間的偶數:
for (int x = 1; x <= 10; x++) {
if (x % 2 == 1) continue; // 跳過奇數
System.out.println("x=" + x);
}
關鍵點:continue 跳過本次循環,break 退出整個循環。
計算 1+2+...+10:
// while 版本
int sum = 0, x = 1;
while (x <= 10) {
sum += x;
x++;
}
// for 版本(推薦)
int sum = 0;
for (int x = 1; x <= 10; x++) {
sum += x;
}
System.out.println("sum=" + sum); // 55
核心思想:變量記錄狀態,循環驅動狀態變更。
統計 1-100 中 7 的倍數個數:
int count = 0;
for (int x = 1; x <= 100; x++) {
if (x % 7 == 0) count++;
}
System.out.println("count=" + count); // 14
應用場景:符合條件的元素計數、分頁總數統計等。
// 外層:行數 (3行)
// 內層:每行列數 (4列)
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 4; y++) {
System.out.print("*");
}
System.out.println(); // 換行
}
輸出:
**** **** ****
for (int x = 0; x < 5; x++) { // 5行
for (int y = x; y < 5; y++) { // 列數遞減
System.out.print("*");
}
System.out.println();
}
輸出:
***** **** *** ** *
規律:內層初始值跟隨外層變量 y = x。
// 正三角形
for (int x = 0; x < 5; x++) {
for (int y = 0; y <= x; y++) { // 列數遞增
System.out.print("*");
}
System.out.println();
}
// 數字三角形
for (int x = 1; x <= 5; x++) {
for (int y = 1; y <= x; y++) {
System.out.print(y);
}
System.out.println();
}
// 九九乘法表
for (int x = 1; x <= 9; x++) {
for (int y = 1; y <= x; y++) {
System.out.print(y + "*" + x + "=" + (y*x) + "\t");
}
System.out.println();
}
// 上半部
for (int x = 0; x < 5; x++) {
// 打印空格
for (int y = x + 1; y < 5; y++) System.out.print(" ");
// 打印星號
for (int z = 0; z <= x; z++) System.out.print("* ");
System.out.println();
}
// 下半部對稱邏輯類似...
輸出:
*
* *
* * *
* * * *
* * * * *
3000米繩索,每天減半,幾天小於5米?
int day = 0;
for (int x = 3000; x >= 5; x /= 2) {
day++;
}
System.out.println("day=" + day); // 10天
解題模板:
| 常見錯誤 | 正確做法 | 說明 |
|---|---|---|
| 循環變量外洩 | for 內部聲明 for(int x=...) | 限制作用域,避免污染外部 |
| 死循環 | 確保終止條件最終滿足 | 檢查變量更新邏輯 |
| off-by-one 錯誤 | 邊界測試:0, 1, max, max+1 | <= vs < 需仔細斟酌 |
| 嵌套層級過深 | 提取方法、Stream API 替代 | >3層嵌套考慮重構 |
| 性能敏感場景用增強 for | 傳統 for 可控索引,性能略優 | 數組/集合遍歷增強 for 更簡潔 |
// 累加求和
int sum = IntStream.rangeClosed(1, 10).sum();
// 計數器
long count = IntStream.rangeClosed(1, 100).filter(x -> x % 7 == 0).count();
// 九九乘法表
IntStream.rangeClosed(1, 9).forEach(x ->
IntStream.rangeClosed(1, x).forEach(y ->
System.out.print(y + "*" + x + "=" + (y*x) + "\t")
)
);
循環是程式設計的心跳。掌握嵌套邏輯、狀態管理與邊界控制,是從「寫出代碼」到「寫出正確、高效、可維護代碼」的關鍵躍遷。