如何计算2D数组中每列的总和?

时间:2017-05-05 13:33:57

标签: java arrays loops

我正在编写一个程序,以便计算并打印数组每列的总和。给定的数据如下所示:

int[][] data = {{3, 2, 5},
                {1, 4, 4, 8, 13},
                {9, 1, 0, 2},
                {0, 2, 6, 3, -1, -8}};

理想情况下,它应输出结果13,9,15,13,​​12,-8。但由于某些行具有不同的长度,当我运行我的程序时,它输出13,9,15并给出一个ArrayIndexOutOfBoundsException。我真的不知道如何解决它。

这是我的代码:

public class ColumnSums
{
public static void main(String[] args) {

    //The given data
    int[][] data = {{3, 2, 5},
                    {1, 4, 4, 8, 13},
                    {9, 1, 0, 2},
                    {0, 2, 6, 3, -1, -8}};

    //Determine the number of data in the longest row
    int LongestRow = 0;
    for ( int row=0; row < data.length; row++){
        if ( data[row].length > LongestRow ){
            LongestRow = data[row].length;
        }
    }
    System.out.println("The longest row in the array contains " + LongestRow + " values"); //Testing

    //Save each row's length into a new array (columnTotal)
    int[] columnTotal = new int[4];

    //Scan through the original data again
    //Record each row's length into a new array (columnTotal)
    System.out.println("The lengths of each row are: ");
    for ( int i = 0; i < data.length; i++){
        columnTotal[i] = data[i].length;
        System.out.println(columnTotal[i]); //Testing
    }


    // Create an array to store all the sums of column
    int ColumnSums[] = new int[LongestRow];
    System.out.println("The sums of each column are: ");

    for ( int i = 0; i < LongestRow; i++ ){

            int sum = 0;

            for (int j = 0; j < data.length; j++) {
                    sum = sum + data[j][i];
            }

            ColumnSums[i] = sum;
            System.out.println("Column " + i + ": " + ColumnSums[i]); //Testing
    }


}
}

谢谢你的时间!!!

3 个答案:

答案 0 :(得分:1)

你基本上只需要循环遍历列,直到计数器超出每行的范围。无需提前循环找到最长的行。

   public static ArrayList<Integer> getCollumnSum() {
        int[][] data = {{3, 2, 5},
                        {1, 4, 4, 8, 13},
                        {9, 1, 0, 2},
                        {0, 2, 6, 3, -1, -8}};
        int col = 0;
        ArrayList<Integer> totals = new ArrayList<Integer>();
        while (true) {
          int total = 0;
          boolean dataInCol = false;
          for (int i = 0; i < data.length; i++) {
            if (col < data[i].length) {
                total += data[i][col];
                dataInCol = true;
            }
          }
          col += 1;
          if (dataInCol) {
            totals.add(total);
          } else {
            break;
          }
        }
        return totals;
      }

输出:

[13, 9, 15, 13, 12, -8]

答案 1 :(得分:0)

要读取2D数组,您的循环应该是

for(int i = 0; i < array.length; ++i){
    for(int j = 0; j < array[i].length; ++j){
        System.out.println(array[i][j]);
    }
}

请参阅使用for(int j = 0; j < array[i].length; ++j)来使用当前行长度。

有了这个,您将阻止此ArrayIndexOutOfBoundsException

如果您需要我可以提问。刚发表评论!

答案 2 :(得分:0)

我已修改您的代码以满足您的需求

int[][] data =  {{3, 2, 5},
                {1, 4, 4, 8, 13},
                {9, 1, 0, 2},
                {0, 2, 6, 3, -1, -8}};

int longestRow = 0;
for ( int row=0; row < data.length; row++){
    if ( data[row].length > longestRow ){
        longestRow = data[row].length;
    }
}
System.out.println("The longest row in the array contains " + longestRow + " values"); 

此处不需要columnTotal,因为我无法注意到它的使用。这可能是你的程序需要。无论如何,您可以直接打印每行的长度,如下所示。

System.out.println("The lengths of each row are: ");
for ( int i = 0; i < data.length; i++){
     System.out.println("Row " + i + " is " + data[i].length); 
    }

您无法获得每个内循环中每列的总和,因为在两个循环完成后将获得每列的总和。因此,变量sum是无用的。所以,它就像下面的

int columnSums[] = new int[longestRow];
for ( int i = 0; i < data.length; i++ ){
        for (int j = 0; j < data[i].length; j++){
                columnSums[j] +=data[i][j];
            }
    }

最后,您可以打印每列的总和,如下所示

System.out.println("The sums of each column are: ");

for (int i = 0; i < columnSums.length; i++) {
        System.out.println("Column " + i + ": " + columnSums[i]);
    }

运行代码后,输出为:

The longest row in the array contains 6 values
The lengths of each row are: 
Row 0 is 3
Row 1 is 5
Row 2 is 4
Row 3 is 6
The sums of each column are: 
Column 0: 13
Column 1: 9
Column 2: 15
Column 3: 13
Column 4: 12
Column 5: -8