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;
}
}
하는 행에서 컴파일 에러가 발생 :
모습할까요? 간단히 말해서,'int'를'int'에 추가 할 수는 있지만'int'를 배열로 추가 할 수는 없습니다. – Simon
'matrix +'가 2 차원 배열이고 1 차원 만 접근하기 때문에'sum + = matrix [i];'는 오류의 원인입니다. 또한, getSumMatrixDiag 메소드를 컴파일하고 홀수로 설정하면 getSumMatrixDiag 메소드에서'ArrayIndexOutOfBoundsException'을 얻습니다. – Kevin
@ Simon 감사합니다! getSumMethod를 편집하여 "int sum = 0; for (int i = 0; i