例如: //一维数组
public class One { public static void main(String[] args) {
int arr[] = {7,1,10};
System.out.println("一维数组中的元素分别为:");
for(int x:arr){
System.out.println(x+" ");
}
}
}
//二维数组
public class Two{
public static void main(String args[]){
int arr[][] = {{3,4,5},{1,2,5}};
System.out.println("二维数组中的元素分别为:");
for(int x[]:arr){
for(int e : x){
System.out.println(e+" ");
}
System.out.println("");
}
}
} 然而你会问为什么用foreach遍历二维数组? 当然是因为普通的for循环太麻烦。二维数组遍历要用双层 for循环,还要通过数组的length属性获得数组的长度。我觉得我自己还是挺懒的。
但是还是要给个例子。 //用双层for循环遍历二维数组
public class Three{
public static void main(String args[]){
int b[][] = new int[][]{{1,},{2,3},{4,5,6}};
System.out.println("二维数组为:");
for(int k = 0;k<b.length; k++){
for(int c = 0; c<b[k].length;c++){
System.out.println(b[k][c]+" ");
}
System.out.println();
}
}
} 所以foreach语句遍历数组更简单,双层我都迷了。