Java 循环结构

while、do-while、for、for-each 循环与 break/continue。

Beginner
Key Pointswhile 先判断后执行、do-while 至少执行一次、for 适合已知次数、for-each 适合遍历;break 跳出、continue 跳过本轮。

while 循环

while (cond) tests before each pass and runs the body only when true. The body must move the condition toward false, or the loop never ends.

Java
public class WhileDemo {
    public static void main(String[] args) {
        int x = 10;

        while (x < 15) {
            System.out.print("value of x : " + x + "\n");
            x++;
        }
    }
}
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14

do…while 循环

do { } while (cond); runs the body once before testing, so it always executes at least once. The trailing semicolon is required.

Java
public class DoWhile {
    public static void main(String[] args) {
        int x = 10;

        do {
            System.out.print("value of x : " + x + "\n");
            x++;
        } while (x < 12);

        int y = 100;
        do {
            System.out.println("runs once even though 100 < 12 is false");
        } while (y < 12);
    }
}
Output
value of x : 10
value of x : 11
runs once even though 100 < 12 is false

for 循环

for (init; cond; update) puts all three parts on one line and suits counted loops. Any part may be omitted, but the semicolons stay.

Java
public class ForDemo {
    public static void main(String[] args) {
        for (int x = 10; x < 15; x = x + 1) {
            System.out.print("value of x : " + x + "\n");
        }

        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            sum += i;
        }
        System.out.println("sum = " + sum);
    }
}
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
sum = 15

Java 增强 for 循环

for (Type v : arrayOrCollection) walks elements without indices and cannot go out of bounds. The trade-off is no index and no safe removal during iteration.

Java
public class ForEach {
    public static void main(String[] args) {
        int[] nums = {10, 20, 30};
        for (int n : nums) {
            System.out.print(n + " ");
        }
        System.out.println();

        String[] names = {"a", "b"};
        for (String s : names) {
            System.out.println(s.toUpperCase());
        }
    }
}
Output
10 20 30 
A
B

break 与 continue

break leaves the whole loop; continue skips the rest of the current pass. Both affect only the innermost loop unless you use a label like outer:.

Java
public class BreakContinue {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            if (i == 3) break;
            System.out.print(i + " ");
        }
        System.out.println();

        for (int i = 0; i < 5; i++) {
            if (i % 2 == 0) continue;
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
Output
0 1 2 
1 3 

Friends & Partners