for(int i : arr) for循环遍历数组

Java5 引入了一种主要用于数组的增强型 for 循环。

for(声明语句 : 表达式) { //代码句子 }

声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。

表达式:表达式是要访问的数组名,或者是返回值为数组的方法。

public class TestForLoop {
	public static void main(String[] args) {
		int[] arr = new int[]{0, 1, 2, 3, 4};	
		
		for(int i = 0; i < arr.length; ++i) {
			System.out.println(arr[i]);
		}//输出01234
		
		for(int j : arr) {
			System.out.println(j);
		}//输出01234
		
		for(int i = 0; i < arr.length; ++i) {
			System.out.println(arr[0]);
		}//输出5次arr[0]
		
		for(int j : arr) {
			System.out.println(0);
		}//输出5次arr[0]
		
	}
}

参考文章:
https://www.runoob.com/java/java-loop.html

发布了5 篇原创文章 · 获赞 2 · 访问量 203

猜你喜欢

转载自blog.csdn.net/Blue3Red1/article/details/105051394
Arr