二维(two Dimensional)数组应用场景:
什么是二维数组:
输出二维数组:
关于二维数组的相关概念:
动态初始化:
int[][] arr = new int[3][3];
二维数组内存布局:
动态初始化:
int[][] arr; arr = new int[2][3];
动态初始化——列数不确定:
int[][] arr = new int[3][];
静态初始化:
int[][] arr = {{0,0,0,0,0,0}, {0,0,1,0,0,0,1}, {0,2,0,3,0,0}, {0,0,0,0,0}};
package 数组.二维数组; public class P5 { public static void main(String[] args) { int[][] arr = {{4,6},{1,4,5,7},{-2}}; 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] + " "); sum += arr[i][j]; } System.out.println(); } System.out.println(sum); } }
思路分析:
代码实现:
package 数组.二维数组; public class YangHui { public static void main(String[] args) { int[][] arr = new int[10][]; for (int i = 0; i < arr.length; i++) { arr[i] = new int[i+1]; for (int j = 0; j < arr[i].length; j++) { arr[i][j] = 1; if (i > 1 && j > 0 && j < arr[i].length-1){ arr[i][j] = arr[i-1][j]+arr[i-1][j-1]; } } } showArr(arr); } static void showArr(int[][] arr){ 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(); } } }