我是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());
}
}
答案 0 :(得分:5)
问题在于:
int[][] a1 = { { 1, 2 }, { 3, 4 } };
Matrix m1 = new Matrix(a1);
Java没有看到接受int[][]
的构造函数。您的构造函数只接受int[]
。因此,错误消息。
您可能需要相应地更改构造函数(以及矩阵字段):
int[][] matrix;
Matrix(int[][] matrix) {
this.matrix = matrix;
}
答案 1 :(得分:0)
您也可以使用第三方库。例如,la4j:
Matrix a = new Basic2DMatrix(new double[][] {
{ 1.0, 2.0 },
{ 3.0, 4.0 }
});
System.out.println(a.sum()); // easy-peasy