我是 java 新手,我必须找到 2D 数组的总和,但我的代码根本无法编译。我不断收到错误:
发现 3 个错误:
File: C:\Users\Brett\Documents\DrJava\Matrix.java [line: 9]
Error: length cannot be resolved or is not a field
File: C:\Users\Brett\Documents\DrJava\Matrix.java [line: 10]
Error: The type of the expression must be an array type but it resolved to int
File: C:\Users\Brett\Documents\DrJava\Matrix.java [line: 15]
Error: The constructor Matrix(int[][]) is undefined
我不知道如何解决它们,在此先感谢您的帮助!
public class Matrix {
int[] matrix;
Matrix(int[] matrix) {
this.matrix = matrix;
}
int sum() {
int sum = 0;
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
sum += matrix[i][j];
return sum;
}
public static void main(String[] args) {
int[][] a1 = { { 1, 2 }, { 3, 4 } };
Matrix m1 = new Matrix(a1);
System.out.println(m1.sum());
}
}