我如何引用我在其上实现实例方法的对象。我编写了一个名为 MatrixMaker
的类,如下所示:
package one;
public class MatrixMaker {
private int rows;
private int columns;
public MatrixMaker(int m, int n){
rows = m;
columns = n;
double[][] matrix = new double[rows][columns];
}
public void printer(){
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
我在这个类中初始化了一个对象:
MatrixMaker matrix = new MatrixMaker(3,4);
我的问题是如何使用
matrix.printer();
打印数组。我似乎无法在方法 printer()
中引用对象的内容。具体行:
System.out.print(matrix[i][j]);
最佳答案
您的 double[][] 矩阵
变量是构造函数的局部变量,因此它只存在于构造函数的范围内。将其设为实例变量,以便从其他方法访问它。
public class MatrixMaker {
private int rows;
private int columns;
private double[][] matrix;
public MatrixMaker(int m, int n){
rows = m;
columns = n;
matrix = new double[rows][columns];
}
这将使 printer
方法可以访问它。
...
关于java - 使用简单的打印方法打印数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26704260/