2014-11-02 93 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 

你也可以在一個提供輸入的號碼之一,因爲: ..