循环结构是指在程序中需要反复执行某个功能而设置的一种程序结构。
Java中主要的循环结构:
- while循环(适用情况,固定次数循环)
- do…while循环(适用情况,“当.....”循环)
- for循环(适用情况,“直到....”循环)
while循环
while是最基本的循环,它的结构为:
1while( 布尔表达式 ) { 2 //循环内容 3}
【只要布尔表达式为true,循环体会一直执行下去。】
实例
1public class Test { 2 public static void main(String args[]) { 3 int x = 10; 4 while( x < 20 ) { 5 System.out.print("value of x : " + x ); 6 x++; 7 System.out.print("\n"); 8 } 9 } 10}
do…while循环
对于while语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次。
do…while循环和while循环相似,不同的是,do…while循环至少会执行一次。
1do { 2 //代码语句 3}while(布尔表达式);
【布尔表达式在循环体的后面,所以语句块在检测布尔表达式之前已经执行了。 如果布尔表达式的值为true,则语句块一直执行,直到布尔表达式的值为false。】
实例
1public class Test { 2 3 public static void main(String args[]){ 4 int x = 10; 5 6 do{ 7 System.out.print("value of x : " + x ); 8 x++; 9 System.out.print("\n"); 10 }while( x < 20 ); 11 } 12}
for循环
虽然所有循环结构都可以用while或者do...while表示,但Java提供了另一种语句 —— for循环,使一些循环结构变得更加简单。
for循环执行的次数是在执行前就确定的。语法格式如下:
1for(初始化; 布尔表达式; 更新) { 2 //代码语句 3}
关于for循环有以下几点说明:
- 最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。
- 然后,检测布尔表达式的值。如果为true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。
- 执行一次循环后,更新循环控制变量。
- 再次检测布尔表达式。循环执行上面的过程。
实例
1public class Test { 2 3 public static void main(String args[]) { 4 5 for(int x = 10; x < 20; x = x+1) { 6 System.out.print("value of x : " + x ); 7 System.out.print("\n"); 8 } 9 } 10}