一、二维数组的定义
public class TwoArrayTest {
public static void main(String[] args) {
//二维数组声明与初始化
//方式1:静态初始化
int[][] arr = new int[][]{{1,2,3},{1,2,3},{1,2,3}};
//方式2:动态初始化
int[][] arr2 = new int[3][3];
arr2[0][1] = 4;
//数组元素调用
System.out.println(arr2[0][1]);
//数组的长度
System.out.println(arr2.length);
System.out.println(arr2[0].length);
//数组的遍历
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();
}
//数组元素的默认初始化值
/**
* 外层元素:默认存储的是地址值
* 内层元素:默认存储的与一维数组默认值相同
*/
int[][] arr3 = new int[2][1];
System.out.println(arr3[0]);//地址值
System.out.println(arr3[0][0]);//0
}
}
二、二维数组练习
2.1、求元素总和
public class ArrayExer04 {
public static void main(String[] args) {
int[][] arr = {{3,5,8},{12,9},{7,0,6,4}};
//记录元素总和
int sum = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + "\t");
sum += arr[i][j];
}
System.out.println();
}
System.out.println("元素总和为:" + sum);
}
}