获取2D数组中每个单独行和列的总和

时间:2014-11-24 06:00:53

标签: java arrays multidimensional-array

我有一行和一列的总和,但我希望分别找到每行和每列的总和。例如,输出将是"第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);    
  }
}

2 个答案:

答案 0 :(得分:0)

你错过了一条线,使用这样:

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

类似地,

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

答案 1 :(得分:0)

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

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