while

while (条件表达式) {
    循环语句
}
// 继续执行后续代码

使用while计算从m到n的和

public class Main {

    public static void main(String[] args) {
        int sum = 0;
        int m = 20;
        int n = 100;
        while (m <= n) {
            sum += m++;
        }
        System.out.println(sum);
    }

}

do while

先执行循环,再判断条件,条件满足时继续循环,条件不满足时退出

do {
    执行循环语句
} while (条件表达式);

do while循环会至少循环一次

使用do while循环计算从m到n的和

public class Main {

    public static void main(String[] args) {
        int sum = 0;
        int m = 1;
        int n = 100;
        do {
            sum+=m++;
        } while (m<=n);
        System.out.println(sum);
    }

}
Last modification:March 4th, 2020 at 11:27 pm
If you think my article is useful to you, please feel free to appreciate