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

    1. while (expression) {
    2. statement(s)
    3. }

    while语句对expression求值,该expression必须返回一个boolean值。如果表达式的计算结果为truewhile语句执行(多个)while语句块。while语句继续测试表达式并执行其块,直到表达式的值为false。使用while语句打印从1到10的值,可以通过以下 WhileDemo程序完成:

    1. class WhileDemo {
    2. public static void main(String[] args){
    3. int count = 1;
    4. while (count < 11) {
    5. System.out.println("Count is: " + count);
    6. count++;
    7. }
    8. }
    9. }

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

    1. while (true){
    2. // your code goes here
    3. }

    Java编程语言还提供了一条do-while语句,该语句可以表示如下:

    1. do {
    2. statement(s)
    3. } while (expression);

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

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