問題是我試圖打印先前在構造函數中創建的矩陣,但似乎是空的。嘗試打印數組時嘗試在Java中出現NullPointerException
這裏的構造函數的代碼:
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]);
}
問候!
感謝您的答案,現在似乎工作,但以一種奇怪的方式。我將維度設置爲2x2,但是當我調用print方法時,它會打印如此巨大的數字鏈......我在構造函數中有什麼錯誤嗎? –
@Ziitox你還期望什麼?在使用print()方法時,你從不會調用'System.out.println()'或在你的輸出中使用''\ n「'。 – jlordo