1

我是 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());
  }
}
4

2 回答 2

5

问题是这样的:

int[][] a1 = { { 1, 2 }, { 3, 4 } };
Matrix m1 = new Matrix(a1);

Java 没有看到接受int[][]. 您的构造函数只接受int[]. 因此,错误消息。

您可能希望相应地更改您的构造函数(和矩阵字段):

int[][] matrix;
Matrix(int[][] matrix) {
    this.matrix = matrix;
}
于 2013-09-20T01:44:13.700 回答
0

您也可以为此使用第三方库。例如,la4j

Matrix a = new Basic2DMatrix(new double[][] {
  { 1.0, 2.0 },
  { 3.0, 4.0 }
});

System.out.println(a.sum()); // easy-peasy
于 2013-09-20T03:52:24.780 回答