Java循环结构-for,while和do...while
顺序结构的程序语句只能被执行一次。如果您想要同样的操作执行多次,就需要使用循环结构。
- while循环
- do...while循环
- for循环
在Java5中引入了一种主要用于数组的增强型for循环(for-each循环?三目运算符?)
Java增强for循环
Java增强for循环语法格式如下:
1for(声明语句:表达式) 2{ 3//代码句子 4}
声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。
表达式:表达式是要访问的数组名,或者是返回值为数组的方法。
实例
1package pkg2020华南虎; 2 3/** 4 * 5 * @author yl 6 */ 7public class ImproveFor { 8 9 public static void main(String[] args) { 10// int []nums=new int[5]; 11 int[] nums = {10, 20, 30, 40, 50}; 12 for (int x : nums) { 13 System.out.print(x + " "); 14 } 15 System.out.print("\n"); 16 String[] names = {"James", "Larry", "Tom", "Lacy"}; 17 for (String name : names) { 18 System.out.print(name + " "); 19 } 20 } 21}
break关键字
break主要用在循环语句或者switch语句中,用来跳出整个语句块。
break跳出最里层的循环,并且继续执行该循环下面的语句。
1package pkg2020华南虎; 2 3/** 4 * 5 * @author yl 6 */ 7public class TestBreak { 8 9 public static void main(String[] args) { 10 int[] nums = {10, 20, 30, 40, 50}; 11 for (int x : nums) { 12 if (x == 30) { 13 break; 14 } 15 System.out.println(x); 16 } 17 } 18}
continue关键字
continue适用于任何循环控制结构中,作用是让程序立刻跳转到下一次循环的迭代。
在for循环中,continue语句使程序立即跳转到更新语句。
在while或者do...while循环中,程序立即跳转到布尔表达式的判断语句。
1package pkg2020华南虎; 2 3/** 4 * 5 * @author yl 6 */ 7public class TestContinue { 8 public static void main(String[] args) { 9 int[]nums={10,20,30,40,50}; 10 for(int x:nums){ 11 if(x==30) continue; 12 System.out.println(x); 13 } 14 } 15}