在尝试获得总和时出错

时间:2013-06-06 03:24:49

标签: java arrays multidimensional-array sum

我正在尝试获取名为matrix的数组之和。但是,当我编译它时,我收到此错误:bad operand types for binary operator '+' first type: int; second type:int[]。我不明白为什么这会导致错误。请帮助我理解,这是我的代码:

/**
Sophia Ali


1. Matrix, getSumMatrix, getSumMatrixDiag:

   Email just Matrix.java.

   Write a class called Matrix that contains a private 2-dimensional int
   array called 'matrix' that can be up to 10 rows by 10 columns maximum.
   Use two constants MAXROWS=10 and MAXCOLS=10 to construct 'matrix.'

   The Matrix class will also need the following attributes:

      private int rows; // number of rows to use in matrix
      private int cols; // number of cols to use in matrix

   The rows and cols will contains values that are less than equal to
   MAXROWS and MAXCOLS.


   Write a default Matrix class constructor that constructs the 'matrix'
   array with the following values:

      {{1,2,4,5},{6,7,8,9},{10,11,12,13}, {14,15,16,17}}

   The constructor must also set the rows and cols variables to match the
   above matrix.


   Write a method 'getSumMatrix' that returns the sum of all the integers
   in the array 'matrix'.


   Write a method 'getSumMatrixDiag' that returns the sum of all the
   integers in the major diagonal of the array 'matrix'. A major diagonal is
   the diagonal formed from the top left corner to the bottom right corner of
   the matrix.


   You do not have to write a TestMatrix class to test the Matrix class.
   Just use the BlueJ object creation and testing feature.
 */
public class Matrix
{

    static final int MAXROWS = 10;
    static final int MAXCOLS = 10;
    private int rows;
    private int cols;

    private int [][] matrix = new int [MAXROWS][MAXCOLS];

    public Matrix()
    {
    int matrix[][] = 
     {
         {1, 2, 4, 5},
         {6, 7, 8, 9},
         {10, 11, 12, 13},
         {14, 15, 16, 17}};
         getSumMethod(matrix);
         getSumMatrixDiag(matrix);
     }

     public int getSumMethod(int[][] matrix)
     {
      int sum = 0;
      for (int i = 0; i < matrix.length; i++) {
          sum += matrix[i];
        }
        return sum;
    }

            /*
         int i, result;
         result = 0;
         for(i=0; i < matrix.length; i++)
         {
             i++;
             result = result + i;
         }
         return result;
     }
     */

     public int getSumMatrixDiag(int[][] matrix)
     {
         int sum = 0;

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


        }

1 个答案:

答案 0 :(得分:1)

在对多维矩阵求和时,必须遍历所有维度。因此,在您的情况下,您有一个二维数组,因此您需要两个嵌套循环来遍历两个数组。 你的循环:

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

应该是这样的:

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