簡體   English   中英

使用簡單的打印方法打印數組對象

[英]Printing an array object using a simple print method

如何引用要在其上實現實例方法的對象。 我編寫了一個名為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[][] 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方法可以訪問它。 ...

您的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];
    }

您將matrix定義為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();
    }
} 

您必須在類內部聲明變量矩陣以使其成為成員變量,而不是在構造函數中作為局部變量。

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

嘗試這個:

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

或者,您可以一一提供輸入數字,例如:1 2 3 4 5 6 ..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM