我有以下代码。它是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