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);
    }

}
THE END
最后修改:2020 年 03 月 04 日 23 : 27
本文链接:https://www.j000e.com/%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6/whiledowhile.html
版权声明:本文『[while][do while]』为『Joe』原创。著作权归作者所有。
转载说明:[while][do while] || Joe's Blog』转载许可类型见文末右下角标识。允许规范转载时,转载文章需注明原文出处及地址。
Last modification:March 4, 2020