我有以下代碼。它是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鍵
這是一個'float [] []',而不是'Float [] []' - 你可能會讓編譯器初始化所有的子陣列,按照我的答案。 – 2013-03-05 03:52:06
@JonSkeet我的不好,代碼固定。 – 2013-03-05 03:52:29