Java 增强 for 循环
Java5 所引入的一种主要用于数组的增强型for循环。(可用来遍历数组)
Java 增强for循环语法如下:
复制代码
1
2
3
4
5for(声明语句 : 表达式) { //代码句子 }
声明语句:
声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。
表达式:
表达式是要访问的数组名,或者是返回值为数组的方法。
Java文件代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class Test { public static void main(String[] args){ int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ){ System.out.print( x ); System.out.print(","); } System.out.print("n"); String [] names ={"James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } }
创建类,并创建出该类的数组,再用增强for循环遍历出
创建类Employee(其子类:SalariedEmployee,HourlyEmployee,SalesEmployee,BasePlusSalesEmployee),并在Test2中创建一个Employee 数组,分别创建若干不同的Employee子类对象,通过使用Java增强for循环来遍历打印出来。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20package two; public class Test2 { public static void main(String[] args) { // TODO Auto-generated method stub Employee[] em = new Employee[4];//创建一个Employee 数组em em[0]=new SalariedEmployee("张三",5,5000);//创建一个子类的对象 em[1]=new HourlyEmployee("李四",3,30,172); em[2]=new SalesEmployee("王五",4,10000,0.3); em[3]=new BasePlusSalesEmployee("王二",5,20000,0.03,5000); for(Employee e:em) { System.out.println(e.getName()+"的5月工资:"+e.getSalary(5)+"元"); } } }
最后
以上就是文静手链最近收集整理的关于Java增强 for 循环Java 增强 for 循环的全部内容,更多相关Java增强内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复