1、java中使用foreach循环来访问数组类似代码块如下:
public class tryDforeach {
public static void main(String[] args){
int[] arr={2,3,1};
System.out.print("一维数组中的元素分别为:");
for(int x:arr){
//foreach 语句,int x引用变量,arr 指定循环遍历的数组,最后将x输出。
System.out.print(x+" ");
}
}
}
2、使用双层foreach遍历2维数组代码块如下:
public class tryDforeach {
public static void main(String[] args) {
int[][] array={{4,2},{3,1}};
for (int[] i : array) {
for (int j : i) {
System.out.print(j+"\t");
}
}
}
}
//foreach 的使用机制最终以在for循环中定义的变量来代替数组中的数,即j的值就是数组中的值