Robin1985

导航

 

声明并创建二维数组

​ 声明二维数组的语法:

  • 数据类型[][] 数组名;

  • 数据类型 数组名[][];

    ​二维数组中使用两个下标,一个表示行,另一个表示列。同一维数组一样,每个下标索引值都是int类型的,从0开始。

    ​创建二维数组语法:

  • 数据类型[][] 数组名 = new 数据类型[外部数组大小][内部数组大小];

  • 数据类型 数组名[][] = new 数据类型[外部数组大小][内部数组大小];

    或者可以将二维数组理解成表格。左侧方框内定义行,右侧方框内定义列。

处理二维数组

​ 处理二维数组常用举例:

使用输入值初始化数组

 1 /**
 2  * 输入值初始化二维数组
 3  */
 4 public static void initTwoDimensionArray() {
 5     Scanner input = new Scanner(System.in);
 6     System.out.println("输入外部(行数)长度");
 7     int outer = input.nextInt();
 8     System.out.println("输入内部(列数)长度");
 9     int inner = input.nextInt();
10     int[][] array2 = new int[outer][inner];
11     for (int i = 0; i < array2.length; i++) {
12         for (int j = 0; j < array2[i].length; j++) {
13             array2[i][j] = input.nextInt();
14         }
15     }
16 }

使用随机值初始化数组

 1 /**
 2  * 输入值随机初始化二维数组(随机值为0-99)
 3  */
 4 public static void randomInitTwoDimensionArray() {
 5     Scanner input = new Scanner(System.in);
 6     System.out.println("输入外部(行数)长度");
 7     int outer = input.nextInt();
 8     System.out.println("输入内部(列数)长度");
 9     int inner = input.nextInt();
10     int[][] array2 = new int[outer][inner];
11     for (int i = 0; i < array2.length; i++) {
12         for (int j = 0; j < array2[i].length; j++) {
13             array2[i][j] = (int) (Math.random() * 100);
14         }
15     }
16 }

打印数组

 1 /**
 2  * 循环打印二维数组中的元素
 3  */
 4 public static void printTwoDimensionArray(int[][] array2) {
 5     for (int i = 0; i < array2.length; i++) {
 6         for (int j = 0; j < array2[i].length; j++) {
 7             System.out.print(array2[i][j] + " ");
 8         }
 9         System.out.println();
10     }
11 }

求所有元素的和

 1 /**
 2  * 计算二维数组中所有元素的和 
 3  */
 4 public static int sumTwoDimensionArray(int[][] array2) {
 5     int total = 0;
 6     for (int i = 0; i < array2.length; i++) {
 7         for (int j = 0; j < array2[i].length; j++) {
 8             total += array2[i][j];
 9         }
10     }
11     return total;
12 }

对数组按列求和

 1 /**
 2  * 计算二维数组中每个单独数组元素的和 
 3  */
 4 public static int[] sumSimpleTwoDimensionArray(int[][] array2) {
 5     int[] array = new int[array2.length];
 6     int total = 0;
 7     for (int i = 0; i < array2.length; i++) {
 8         total = 0;
 9         for (int j = 0; j < array2[i].length; j++) {
10             total += array2[i][j];
11         }
12         array[i] = total;
13     }
14     return array;
15 }

 

posted on 2017-03-22 10:58  Robin1985  阅读(94)  评论(0)    收藏  举报