二维数组(参差不齐)- 打印每列总和

2D Array(Ragged) - Print Each Column Sum

我正在尝试计算二维数组的按列求和。

对于这个二维数组:

int[][] array = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};

我可以毫不费力地打印每列总和。

这是我的代码

int total;
for (int col = 0; col < array[0].length; col++)
{
  total = 0;
  for (int row = 0; row < array.length; row++)
    total += array[row][col];
  System.out.println("Column " + col + " total: " + total);
}

但是,对于这个参差不齐的二维数组:

int[][] array = {{1,2},{5,6,7},{9,10,11,12}};

我似乎无法在不出现 outofboundsexception 错误的情况下打印最后两列。我们的教授并没有真正教过我们 try 和 catch 语句,所以我假设必须进行某种小的调整。但是,我已经篡改了上面的代码以打印最后两列,但没有成功...

有什么想法吗?

试试这个:

int total;
int max = //This is the max number of column one row can have 
for (int col = 0; col < max; col++)
{
  total = 0;
  for (int row = 0; row < array.length; row++)
    if(col < array[row].length)//Check for row length here.
       total += array[row][col];
  System.out.println("Column " + col + " total: " + total);
}

基本上,您需要先检查行的长度,然后再访问它的元素。

求最大值:

int max = 0;
for(int i = 0; i < array.length; i++)
    max = Math.max(array[i].length, max);

您不需要捕获任何异常。首先,您应该找出二维数组中最长的行(为此您需要一个初步循环)。

假设是x。然后你在外循环中从 0 迭代到 x-1,在你的内循环中,在访问 array[row][col] 之前,你确保 array[row].length > col.

你的教授可能不会接受这个,因为他(还)没有教你这个,但最优雅的解决方案是让 Java 自己做出低级循环决定。您可以使用 for-each loop:

int total = 0;
int iterator = 0; // this variable is only necessary if you need to know which row you're in
for (int[] row : array) {
    int sum = 0;
    for (int item : row) {
        sum += item;
    }
    System.out.println("Column " + iterator + " total: " + sum);
    total += sum;
    iterator++;
}
System.out.println(total);

它的工作方式是指定一个数组及其元素的类型。所以 int[][]int[] 的数组,这就是为什么要指定 for (int[] row : array)。您可以将其读作 "for each one-dimensional row[] in this two-dimensional array[][]"。在循环中,您在 row[].

的每个 int 上嵌套另一个循环

下面是程序的正确代码::我从上面的帮助中学到了 material 但是我得到了错误,因为代码是零散的,特别是最大值被取为最大值(如果我们在下一个计数器中需要更少的最大值然后这个程序失败了)

package arrayPractice;

public class SumColumArray {
    public static void main (String [] args){
        int [][] matrix = new int [5][];
            matrix[0] = new int[2];
            matrix[1] = new int[3];
            matrix[2] = new int[4];
            matrix[3] = new int[2];
            matrix[4] = new int[1];


    int total = 0;
    int max = 0;
    for(int row = 0; row < matrix.length; row++){
    max = matrix[row].length; // Variable Length of Column Accessing 
    System.out.println(max);
    for(int column = 0; column < max; column++){
    total = 0;
    matrix[row][column] = (int)(Math.random() * 100);
    if(column < matrix[row].length);
    total += matrix[row][column];
    System.out.println("Column " + column + " total: " + total);

    }
     }
   }
}