简体   繁体   English

如何计算二维数组中每一列的总和?

[英]How to calculate the sum of each column in a 2D array?

I'm writing a program so that it computes and prints the sum of each column of the array. 我正在编写一个程序,以便它计算并打印数组每一列的总和。 The given data looks like this: 给定的数据如下所示:

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

Ideally, it should output the results 13, 9, 15, 13, 12, -8. 理想情况下,它应输出结果13、9、15、13、12,-8。 But since some of the rows have different lengths, when I run my program, it outputs 13, 9, 15 and gives me an ArrayIndexOutOfBoundsException. 但是由于某些行的长度不同,因此在我运行程序时,它会输出13、9、15,并给我一个ArrayIndexOutOfBoundsException。 And I really don't know how to fix it. 而且我真的不知道该如何解决。

Here is my code: 这是我的代码:

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
    }


}
}

Thanks for your time!!! 谢谢你的时间!!!

You basically just need to loop through the columns until the counter is out of bounds for every row. 基本上,您只需要遍历各列,直到计数器超出每一行的范围。 No need to loop through ahead of time to find the longest row. 无需提前遍历即可找到最长的行。

   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;
      }

Output: 输出:

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

To read a 2D array your loops should be 要读取2D数组,您的循环应为

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

See the use of for(int j = 0; j < array[i].length; ++j) to use the current row length. 请参见使用for(int j = 0; j < array[i].length; ++j)以使用当前行长度。

With this, you will prevent this ArrayIndexOutOfBoundsException 这样,您可以防止发生ArrayIndexOutOfBoundsException

I am open to question if you need. 如果您需要,我可以质疑。 Just post a comment ! 只需发表评论!

I have altered your code to fit your needs 我已更改您的代码以满足您的需求

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"); 

Here, no need for columnTotal as I can't notice any use of it. 在这里,不需要columnTotal因为我没有注意到它的任何使用。 It maybe your program need. 也许您的程序需要。 Anyway, you can print the length of each row directly as below. 无论如何,您可以直接如下打印每行的长度。

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); 
    }

You can't get the sum of each column at each inner loop, because the sum of each column will be obtained after the both loops finish. 您无法在每个内部循环中获得每一列的总和,因为在两个循环完成之后将获得每一列的总和。 Therefore, the variable sum is useless. 因此,变量sum是无用的。 So, it would be like below 所以,就像下面

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];
            }
    }

Finally, you can print the sum of each column as below 最后,您可以按如下所示打印每列的总和

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

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

After running the code, the output would be: 运行代码后,输出为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM