Java - 循环

while 循环

public static void main(String[] args) {
    int i = 0;
    while (i < 20) {
        if(i > 30) {
            break;
        } else if (i % 2 == 0) {
            System.out.print(i + " ");
            i = i + 1;
        } else {
            i = i + 1;
            continue;
        }
    }
    System.out.println("已经找出20以内的偶数!");
}

结果:0 2 4 6 8 10 12 14 16 18 已经找出20以内的偶数!

1、判断条件只能是 boolean 类型。

2、continue 用于跳过该次循环,break 则是用于退出循环。

3、如果条件判断语句永远为 true,循环将会无限的执行下去。

for 循环

public static void main(String[] args) {
    for(int i=0; i<20; i=i+1) {
        if(i > 30) {
            break;
        } else if (i % 2 == 0) {
            System.out.print(i + " ");
            i = i + 1;
        } else {
            i = i + 1;
            continue;
        }
    }
    System.out.println("已经找出20以内的偶数!");
}

结果:0 2 4 6 8 10 12 14 16 18 已经找出20以内的偶数!

另一种写法

public static void main(String[] args) {
    int[] arr ={11,12,13};
    for(int i: arr) {
        System.out.print(i+" ");
    }
}

结果:11 12 13

do...while 循环

public static void main(String[] args) {
    int i = 0;
    do {
        if(i > 30) {
            break;
        } else if (i % 2 == 0) {
            System.out.print(i + " ");
            i = i + 1;
        } else {
            i = i + 1;
            continue;
        }
    } while (i < 20);
    System.out.println("已经找出20以内的偶数!");
}

结果:0 2 4 6 8 10 12 14 16 18 已经找出20以内的偶数!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章