while 和 do-while 语句

while语句在特定条件为true时连续执行语句块。它的语法可以表示为:

while (expression) {
     statement(s)
}

while语句计算表达式,该表达式必须返回boolean值。如果表达式的计算结果为true,则while语句执行while块中的* statement *(s)。 while语句 continue 测试该表达式并执行其块,直到该表达式的值为false为止。可以使用while语句从 1 到 10 打印值,如下面的WhileDemo程序所示:

class WhileDemo {
    public static void main(String[] args){
        int count = 1;
        while (count < 11) {
            System.out.println("Count is: " + count);
            count++;
        }
    }
}

您可以使用while语句实现无限循环,如下所示:

while (true){
    // your code goes here
}

Java 编程语言还提供了do-while语句,可以将其表示为以下形式:

do {
     statement(s)
} while (expression);

do-whilewhile之间的区别在于do-while在循环的底部而不是顶部评估其表达式。因此,do块中的语句始终至少执行一次,如以下DoWhileDemo程序所示:

class DoWhileDemo {
    public static void main(String[] args){
        int count = 1;
        do {
            System.out.println("Count is: " + count);
            count++;
        } while (count < 11);
    }
}