[英]finding the sum of a 2D array in java
我是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());
}
}
問題是這樣的:
int[][] a1 = { { 1, 2 }, { 3, 4 } };
Matrix m1 = new Matrix(a1);
Java沒有看到接受int[][]
的構造函數。 您的構造函數僅接受int[]
。 因此,錯誤消息。
您可能想要相應地更改構造函數(和矩陣字段):
int[][] matrix;
Matrix(int[][] matrix) {
this.matrix = matrix;
}
您也可以為此使用第三方庫。 例如, la4j :
Matrix a = new Basic2DMatrix(new double[][] {
{ 1.0, 2.0 },
{ 3.0, 4.0 }
});
System.out.println(a.sum()); // easy-peasy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.