Java 获取二维数组中每个单独的行和列的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27098719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:48:35  来源:igfitidea点击:

Get the sum of each individual row and column in a 2D array

javaarraysmultidimensional-array

提问by user3247712

I have the sum of one row and one column but I am looking to find the sum of each row and column individually. For example the output would be "Sum of row 1 is.. Sum of row 2 is.. and so forth. Same goes for the columns as well.

我有一行和一列的总和,但我希望单独找到每行和每列的总和。例如,输出将是“第 1 行的总和是......第 2 行的总和是......等等。列也是如此。

public class TwoD {

  public static void main(String[] args) {
    int[][] myArray = { {7, 2, 10, 4, 3},
                        {14, 3, 5, 9, 16},
                        {99, 12, 37, 4, 2},
                        {8, 9, 10, 11, 12},
                        {13, 14, 15, 16, 17}                
    };

    int row = 0;
    int col;
    int rowSum = 0;
    int colSum = 0;

    for(col = 0; col<5;col++)
      rowSum = rowSum + myArray[row][col];
       for( row = 0; row<5; row++)
        System.out.println("Sum of row " + row + " is " + rowSum);

    col = 0;
    for(row=0; row<5;row++)
     colSum = colSum + myArray[row][col];
      for(col = 0; col<5; col++)
       System.out.println("Sum of column " + col + " is " + colSum);    
  }
}

采纳答案by user3437460

To make it neater, you can store the sum of each rows in a 1D array via a method.

为了使它更整洁,您可以通过一个方法将每一行的总和存储在一维数组中。

public static void main(String[] args)
{
    int[][] table = {......}; //where ... is your array data
    int[] sumOfRows = sumTableRows(table);
    for ( int x = 0; x < table.length; x++ )
    {
        for ( int y = 0; y < table[x].length; y++ )
            System.out.print( table[x][y] + "\t" );
        System.out.println( "total: " + sumTableRows[x] );
    }
}

public static int[] sumTableRows(int[][] table)
{
    int rows = table.length;
    int cols = table[0].length;

    int[] sum = new int[rows];
    for(int x=0; x<rows; x++)
        for(int y=0; y<cols; y++)
            sum[x] += table[x][y];
    return sum;     
}

回答by Mohammed Ali

You missed a line, use like this:

你错过了一行,像这样使用:

for(col = 0; col<5;col++)  {
    for( row = 0; row<5; row++)  {
      rowSum = rowSum + myArray[row][col];
    }
    System.out.println("Sum of row "  + rowSum);
    rowSum=0;  // missed this line...
}

Similarly,

相似地,

for(row=0; row<5;row++)  {
    for(col = 0; col<5; col++)  {
       colSum = colSum + myArray[row][col];
    }
    System.out.println("Sum of column " + colSum);
    colSum=0;
}