Documentation

The Java™ Tutorials
Hide TOC
The while and do-while Statementswhile语句和do-while语句
Trail: Learning the Java Language
Lesson: Language Basics
Section: Control Flow Statements

The while and do-while Statementswhile语句和do-while语句

The while statement continually executes a block of statements while a particular condition is true.当特定条件为真时,while语句持续执行语句块。Its syntax can be expressed as:其语法可以表示为:

while (expression) {
     statement(s)
}

The while statement evaluates expression, which must return a boolean value.while语句计算表达式,该表达式必须返回boolean值。If the expression evaluates to true, the while statement executes the statement(s) in the while block.如果表达式的计算结果为true,则while语句将执行while块中的语句The while statement continues testing the expression and executing its block until the expression evaluates to false.while语句继续测试表达式并执行其块,直到表达式的计算结果为falseUsing the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:使用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++;
        }
    }
}

You can implement an infinite loop using the while statement as follows:可以使用while语句实现无限循环,如下所示:

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

The Java programming language also provides a do-while statement, which can be expressed as follows:Java编程语言还提供do-while语句,该语句可以表示为:

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

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top.do-whilewhile之间的区别在于do-while在循环的底部而不是顶部计算其表达式。Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:因此,do块内的语句始终至少执行一次,如以下DoWhileDemo程序所示:

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

Previous page: The switch Statement
Next page: The for Statement