public class Dome10 {
/*
* 二维数组多种方式实现二维数组的遍历
* 二维数组其实和一维数组区别不大,仅仅是在上面的衍生。
*
*
* */
public static void main(String[] args) {
method();
method1();
method2();
}
//for循环实现对arr数组的遍历
private static void method() {
int [] arr = {1,3,5,7,9};
/*for (int i = 0; i <arr.length ; i++) {
System.out.println(arr[i]);
}*/
for (int a:arr) {
System.out.println(a);//a就相当于arr[i]
}
System.out.println("+++++++++++");
}
//for循环嵌套实现对二维数组的遍历,相当于把一维里面的元素当成数组,在对一维元素的每个数组再次进行遍历
private static void method1() {
int [][] arr = {{1,2,3},{6,9,3,5},{1,9}};
for (int i = 0; i <arr.length ; i++) {
for (int j = 0; j <arr[i].length ; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.println("++++++++++++++++");
}
//使用foreach方法对二维数组进行遍历,foreach一般和for循环差不多,不过foreach看着简单些。
private static void method2() {
int [][] arr = {{1,2,3},{6,9,3,5},{1,9}};
for (int[] fs:arr) {
for (int fss:fs) {
System.out.print(fss+" ");//相当于arr[i][j]
}
System.out.println();
}
System.out.println("++++++++++++++++");
}
}