簡體   English   中英

嘗試打印數組時Java中的NullPointerException

[英]NullPointerException in Java while trying to print an array

事實是,我正在嘗試打印先前在構造函數中創建的矩陣,但似乎它是空的。

這是構造函數的代碼:

public Matrix(int row_col){
    int [][] randomMatrix = new int[row_col][row_col];
    Random rand = new Random();
    if (row_col > 0 && row_col < ROW_LIMIT && row_col < COL_LIMIT)
    for (int i = 0; i < randomMatrix.length; i++) 
     for (int j = 0; j < randomMatrix[0].length; j++)
         randomMatrix[i][j] = rand.nextInt(51);
}

並打印該方法的代碼:

public void print(){
    int row = randomMatrix.length;
    int col = randomMatrix[0].length;
    for(int i=0 ; i < row ; i++)
     for(int j=0 ; j < col ; j++)
        System.out.print(randomMatrix[i][j]);
}

問候!

更換

int [][] randomMatrix = new int[row_col][row_col];

通過

this.randomMatrix = new int[row_col][row_col];

構造函數將初始化並填充局部變量,而不是初始化並填充print()方法使用的實例字段

看起來randomMatrix是直接在構造函數的范圍內定義的,並且沒有存儲在類的字段中。

如果您已經具有randomMatrix作為字段,請在構造方法的第一行中刪除int [] [],以便您引用該字段而不是聲明新變量。

這是因為您已經在構造函數中聲明並初始化了數組randomMatrix ,並且一旦執行了構造函數的代碼,您的randomMatrix數組就會超出print方法的范圍。

因此,當您嘗試在print方法中訪問它時,沒有這樣的randomMatrix對象,因此您會得到NullPointerException

暫無
暫無

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

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