freeCodeCamp/guide/chinese/java/loops/while-loop/index.md

1.5 KiB

title localeTitle
While Loop 而Loop

而Loop

while循环重复执行语句块,直到括号中指定的条件求值为false 。例如:

while (some_condition_is_true) 
 { 
    // do something 
 } 

每个'迭代'(执行语句块)之前都要对括号中指定的条件进行求值 - 只有在条件求值为true时才执行语句。如果计算结果为false ,则程序的执行将从while块之后的语句继续执行。

注意 :要使while循环开始执行,您最初需要条件为true 。但是,要退出循环,必须在语句块中执行某些操作,以便在条件计算结果为false时最终到达迭代(如下所示)。否则循环将永远执行。 (实际上,它会一直运行直到JVM内存不足。)

在以下示例中, expressioniter_While < 10给出。每次执行循环时,我们将iter_While增加1 。当iter_While值达到10时, while循环中断。

int iter_While = 0; 
 while (iter_While < 10) 
 { 
    System.out.print(iter_While + " "); 
    // Increment the counter 
    // Iterated 10 times, iter_While 0,1,2...9 
    iter_While++; 
 } 
 System.out.println("iter_While Value: " + iter_While); 

输出:

0 1 2 3 4 5 6 7 8 9 
 iter_While Value: 10 

:rocket: 运行代码