2012-12-15 133 views
2

問題是我試圖打印先前在構造函數中創建的矩陣,但似乎是空的。嘗試打印數組時嘗試在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]); 
} 

問候!

回答

4

通過

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

構造函數初始化並填充一個局部變量代替初始化和填充由print()方法中使用的實例字段的替換

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

+0

感謝您的答案,現在似乎工作,但以一種奇怪的方式。我將維度設置爲2x2,但是當我調用print方法時,它會打印如此巨大的數字鏈......我在構造函數中有什麼錯誤嗎? –

+1

@Ziitox你還期望什麼?在使用print()方法時,你從不會調用'System.out.println()'或在你的輸出中使用''\ n「'。 – jlordo

0

這是怎麼一回事,因爲你已經聲明和初始化構造函數中的陣列randomMatrix並儘快執行構造器的代碼,你randomMatrix陣列超出print方法的範圍。

所以,當您嘗試訪問它print方法有沒有這樣的randomMatrix對象,所以你得到NullPointerException

1

看起來randomMatrix直接在構造函數中的範圍界定,並且不被存儲在這個班的一個領域。

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

相關問題