Java循环
Java中有三种主要循环结构:
- while循环
- do...while循环
- for循环
while循环
while循环结构为:
1 while(布尔表达式){
2 //循环内容
3 }
只要布尔表达式为true,循环就将一直执行下去,也就是死循环
例:
1 public class whileTest {
2 public static void main(String[] args){
3 int x = 10;
4 while (x < 30 ){
5 System.out.println("value of x is "+ x);
6 x++;
7 }
8 }
9 }
do...while循环
do...while循环与while循环类似,不同的是while循环如不满足条件就不会执行代码块,而do...while循环至少会执行一次代码块;
do...while循环结构为:
1 do {
2 //代码语句
3 } while (布尔表达式);
注:布尔表达式在循环体后面,所以在执行表达式之前,就已经执行, 如果布尔表达式为true,则语句块将执行,直到表达式返回false;
例:
1 public class dowhileTest {
2 public static void main(String[] args){
3 int x = 10;
4 do {
5 System.out.println("value of x is "+ x);
6 x++;
7 } while (x < 30);
8 }
9 }
for循环
for循环的循环次数在执行前就可以确定,所以,for循环比while循环更加简洁
for循环语法结构如下:
1 for(初始化; 布尔表达式; 更新){
2 //代码语句
3 }
需要注意:
- 最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。
- 然后,检测布尔表达式的值。如果为 true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。
- 执行一次循环后,更新循环控制变量。
- 再次检测布尔表达式。循环执行上面的过程。
例:
1 public class forTest {
2 public static void main(String[] args){
3 for(int x = 0; x < 30; x++){
4 System.out.println("value of x is "+ x);
5 }
6 }
7 }
for循环增强
语法格式如下:
1 for(声明语句 : 表达式){
2 //代码语句
3 }
声明语句:主要声明局部变量,该变量类型必须与数组元素类型匹配,;
表达式:主要是访问数组;
例:
1 public class intensifierTest {
2 public static void main(String[] args){
3 int []numbers = {10, 23, 203, 24, 92, 20, 230, 22, 12, 53, 9};
4 for(int x : numbers){
5 System.out.println(x);
6
7 }
8 }
9 }
break关键字
break:译为打破,在Java中是跳出的意思。主要用户循环和switch语句中,来跳出循环。
break跳出最里层的循环,并继续执行循环下面的语句。
例:
1 public class breakTest {
2 public static void main(String[] args){
3 int []numbers = {10, 12, 122, 59, 20, 14, 19};
4 for(int x : numbers){
5 if(x == 20){
6 break;
7 }
8 System.out.println("value of x is " + x);
9 }
10 }
11 }
continue关键字
continue:译为继续的意思,它的作用是让程序立即跳出当前循环,继续下一次循环。
Java中,在for循环语序中, continue回让程序立即跳转到更新语句;
在while或者do...while循环中,程序回立即跳转到布尔表达式的判断语句;
例:
for循环:
1 public class continueTest {
2 public static void main(String[] args){
3 int []numbers = {10, 23, 30, 22, 29, 21, 239, 23};
4 for(int x: numbers){
5 // 如果x为30,跳出循环进行下一次循环, 即不会打印30
6 if(x == 30){
7 continue;
8 }
9 System.out.println("value of x is " + x);
10 }
11 }
12 }
while循环:
1 public class whileContinueTest {
2 public static void main(String[] args){
3 int x = 0;
4 while(x < 20){
5 x++;
6 if(x == 11){
7 continue;
8 }
9 System.out.println("value of x is "+ x);
10
11 }
12 }
13 }