2014-11-02 92 views
1

如何引用我在其上实现实例方法的对象。我写了一个叫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]); 
+0

在你的类范围内定义'double [] [] matrix'。所以把它放在'private int columns;'的地方。 – 2014-11-02 20:53:47

+0

谢谢!我甚至没有想到这一点。 – zyzz 2014-11-02 20:55:09

回答

2

double[][] matrix变量是本地的构造函数,所以它只能在构造函数的范围内存在。使其成为实例变量以便从其他方法访问它。

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方法访问。 ...

+0

它的工作!再次感谢。我应该想到这一点。 – zyzz 2014-11-02 20:55:38

2

matrix阵列是局部变量构造MatrixMaker(int m, int n)内。如果你把它变成一个成员变量,你将能够从其他方法访问它。

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]; 
    } 
2

您将矩阵定义为局部变量给Matrix类的构造函数。这个类不会编译。

尝试定义你的矩阵作为一个字段:

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]; 

    } 

    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(); 
    } 
} 
2

您必须声明你的类里面的变量矩阵,使其成员变量,而不是在构造函数中的局部变量。

public class MatrixMaker(int m, int n) { 
    private int rows; 
    private int columns; 
    private double[][] matrix; 
    ... 
1

试试这个:

import java.util.Scanner; 

public class MatrixMaker { 

private int rows; 
private int columns; 
double[][] matrix; 

public MatrixMaker(int m, int n){ 
rows = m; 
columns = n; 
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(); 
} 

} 

public static void main(String[] args) { 
    MatrixMaker m=new MatrixMaker(4,4); 
    Scanner in=new Scanner(System.in); 
    System.out.println("Enter Matrix Elements:"); 
    for(int i=0;i<m.rows;i++){ 
    for(int j=0;j<m.columns;j++) 
     m.matrix[i][j]=Integer.parseInt(in.next()); 
     } 

    in.close(); 

    m.printer(); 
} 

} 

在控制台中提供输入如下:

1 2 3 4 
1 2 3 4 
1 2 3 4 
1 2 3 4 

你也可以在一个提供输入的号码之一,因为: ..