基本语法
Java中只要给定的条件为true,while循环体语句就会重复地执行。while循环的语法如下:
while(Boolean_expression) {
//循环体
}
在这里,循环体可能是单独一行语句也可能是多行。条件语句也可以是一个表达式,其计算出的任何非零的值都是true。
在执行时,如果条件语句得到的是true,那么就执行循环体内的语句。只要条件为true,就会一直重复执行这个过程。
当条件为false时,程序会跳过循环体继续执行while循环后面的部分。
流程图
需要注意的是:while循环可能不会被执行。也就是当条件一开始就为false时,程序会直接跳过while循环去执行后面部分的代码。
使用示例
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
程序运行结果输出如下:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
本篇小结
更多交流,欢迎加群(584017112):