循环语句允许重复执行一个语句或一组语句。
while是最基本的循环,它的结构为:
while( 布尔表达式 ) {
//循环内容
}
只要布尔表达式为 true,循环体会一直执行下去。
下面是一个例子:
int x = 5;
while(x < 10) {
System.out.println(x);
x++;
}
/*
输出
5
6
7
8
9
*/
当检测布尔表达式为true时它将执行其正文中的语句。然后再次检查声明并重复。
当检测布尔表达式为 false 时,将跳过循环体,并执行 while 循环后的第一条语句。
下面是一个例子:
int x = 5;
while( x < 10 )
{
System.out.println(x);
x++;
}
System.out.println("Loop ended");
/*
输出
5
6
7
8
9
Loop ended
*/
网友评论