2013-03-05 79 views
0

我有以下代碼。它是Matrix類的一個構造器。主線程只調用構造函數,然後打印矩陣(我爲它製作了一個方法)。正在拋出NullPointerException,但我無法弄清楚如何解決它。

public class Matrix{ 
    float [][] mainMatrix; 
    int rows; 
    int columns; 
    public Matrix(){ 
     System.out.printf("\nInput the number of rows \n") ; 
    String rowR = new Scanner(System.in).next().replace(" ", "").replace("\n", "").toString(); 
    rows = Integer.parseInt(rowR); 
    System.out.printf("\n Input the number of columns \n"); 
    String columnR = new Scanner(System.in).next().replace(" ", "").replace("\n", "").toString(); 
    columns = Integer.parseInt(columnR); 
    System.out.printf("Input the rows, seperated by a \" \". Close the row with a \"]\""); 
    System.out.println("Warning!!! Inproper input will cause the program to crash!"); 
    for(int r = 0; r < rows; r++){ 
     Scanner item = new Scanner(System.in); 
     System.out.printf("\n["); 
     String[] raw = item.next().replace("]", "").replace("\n", "").split(" "); 
     for(int c = 0; c < columns; c++){ 
      mainMatrix[r][c] = Float.parseFloat(raw[c]); 
     } 
    } 
    /*Bunch of methods*/ 
} 

出於某種原因,當代碼運行時,它返回一個NullPointerException,並點到線:

mainMatrix[r][c] = Float.parseFloat(raw[c]); 

如果有幫助,輸出看起來是這樣的:

Input the number of columns 
2 

Input the rows, seperated by a " ". Close the row with a "]"Warning!!! Inproper input will cause the program to crash! 

[ 2 3] /*\n*/ 
[Ljava.lang.String;@29173efException in thread "main" java.lang.NullPointerException 
    at mathProgs.linProg.Matrix.<init>(Matrix.java:51) 
    at mathProgs.linProg.MatrixTest.main(MatrixTest.java:10) 

2,3和]是用戶輸入。在「]」之後按Enter鍵

回答

5

的原因是,你還沒有初始化mainMatrix:當你有你的行和列變量初始化。你需要的東西,如:

mainMatrix = new int[rows][columns]; 

否則變量的null它的默認值,所以當你嘗試取消對它的引用(值分配給數組的元素),你得到的NullPointerException

請注意,與其他一些語言不同,一旦您創建了一個數組對象,它就具有固定的大小 - 您不能在稍後添加項目。爲此,您需要一個List實現,如ArrayList。在這種情況下不存在問題,因爲您知道有多少行和列開始 - 但值得注意。

2

您尚未初始化mainMatrix屬性,因此其默認值爲null,因此在使用NPE時會得到NPE。

mainMatrix = new float[rows][columns]; 
+0

這是一個'float [] []',而不是'Float [] []' - 你可能會讓編譯器初始化所有的子陣列,按照我的答案。 – 2013-03-05 03:52:06

+0

@JonSkeet我的不好,代碼固定。 – 2013-03-05 03:52:29