我有以下代码。它是 Matrix 类的构造函数。主线程只调用构造函数,然后打印矩阵(我为它做了一个方法)。
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