元素为 一维数组 的数组就称为 二维数组
二维数组的定义格式
public class TwoArray {
public static void main(String[] args) {
int[][] a = new int[4][4];
}
}
}
遍历输出二维数组
public class TwoArray {
public static void main(String[] args) {
int[][] a = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
}
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
进程已结束,退出代码为 0
给二维数组赋值
public class TwoArray {
public static void main(String[] args) {
int[][] a = new int[4][4];
a = new int[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
}
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
进程已结束,退出代码为 0
输出
System.out.println(a[2][2]);
System.out.println(a[0][0]);
System.out.println(a[3][2]);
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
------------------------
11
1
15
如果想遍历输出
int[][] arr = new int[][]{ {1,2,3,4} , {5,6,7} , {8,9,} , {10} , {12,15,17} };
public class TwoArray {
public static void main(String[] args) {
int[][] arr = new int[][]{ {1,2,3,4} , {5,6,7} , {8,9,} , {10}};
for (int i = 0; i < arr.length; i++) {
int[] arr2 = arr[i];
//arr2 = {1,2,3,4};
for (int j = 0; j < arr2.length; j++) {
int x = arr2[j];
System.out.print(x+"\t");
}
System.out.println();
}
}
}
1 2 3 4
5 6 7
8 9
10
进程已结束,退出代码为 0