JAVA 中一般的一条语句只能执行一次,如果想要同样的操作执行多次,,就需要使用 循环结构 。
Java中有三种主要的循环结构:
- while 循环
- do…while 循环
- for 循环(在Java5中引入了一种主要用于数组的增强型 for循环 )。
1、 while 循环:最基本的循环,它的结构为:
public class Test { public static void main(String args[]) { int x = 5; while( x < 10 ) { System.out.print("value of x : " + x ); x++; System.out.print("n"); } } }
2、 do…while 循环:do…while 循环和 while 循环相似,不同的是,do…while 循环至少会执行一次(也就是先执行再进行条件判断)。
public class Test { public static void main(String args[]){ int x = 5; do{ System.out.print("value of x : " + x ); x++; System.out.print("n"); }while( x < 10); } }
3、 for 循环:使用 for 循环,使一些循环结构变得更加简单。for循环执行的次数是在执行前就确定的。
public class Test { public static void main(String args[]) { for(int x = 5; x < 10; x = x+1) { System.out.print("value of x : " + x ); System.out.print("n"); } } }
* 关于 for 循环的几点说明:
- 最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。
- 然后,检测布尔表达式的值。如果为 true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。
- 执行一次循环后,更新循环控制变量。
- 再次检测布尔表达式。循环执行上面的过程。
4、 增强的 for 循环
int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ){ System.out.print( x ); System.out.print(","); }
最后,介绍一下与 循环语句 相关的两个关键字 break 、 continue 。
break 主要用在循环语句或者 switch 语句中,用来跳出整个语句块。break 跳出最里层的循环,并且继续执行该循环下面的语句。用法如下:
break;
continue 适用于任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代。在 for 循环中,continue 语句使程序立即跳转到更新语句。在 while 或者 do…while 循环中,程序立即跳转到布尔表达式的判断语句。用法如下:
continue;