6.4.1 遍历数组
1.定义二维数组,实现将二维数组中的元素全部输出。
public class Demo {
public static void main(String[] args) {
int a[][]=new int[][] {{1,2,3},{4,5,6},{7,8,9}};
for(int i=0;i<a.length;i++) {
for(int j=0;j<a[i].length;j++) {
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
结果
2.定义二维数组,使用foreach语句遍历二维数组。
public class Demo {
public static void main(String[] args) {
int a[][]=new int[][] {{1,2,3},{4,5,6},{7,8,9}};
int i=0;
for(int x[]:a) {
i++;
int j=0;
for(int y:x) {
j++;
if(i==a.length&&j==x.length) { //判断变量是否是数组中的最后一个元素
System.out.print(y+"."); //输出数组中的最后一个元素
}else {
//如果不是数组中的最后一个元素
System.out.print(y+",");
}
}
System.out.println();
}
}
}
结果