我想獲得我的數組的總和稱爲矩陣。但是,當我編譯它時,我收到此錯誤: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;
}
}
在哪一行沒有編譯錯誤發生?簡而言之,雖然你可以在int中添加一個int,但是你不能在int []中添加一個int,這是一個數組。 – Simon
'sum + = matrix [i];'是錯誤的來源,因爲'matrix'是一個二維數組,並且您只能訪問1維。如果將它編譯並設置爲奇數大小,您也將在getSumMatrixDiag方法中獲取'ArrayIndexOutOfBoundsException'。 – Kevin
@Simon謝謝!我編輯了getSumMethod,現在它讀取「int sum = 0; for(int i = 0; i