我有以下代码。它是 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
最佳答案
原因是您尚未初始化mainMatrix
。你需要这样的东西:
mainMatrix = new int[rows][columns];
否则,该变量的默认值为 null
,因此当您尝试取消引用它(将值分配给数组的元素)时,您会得到 空指针异常
。
请注意,与其他一些语言不同,一旦创建了数组对象,它就有固定的大小 - 您不能稍后向其中添加项目。为此,您需要一个 List
实现,例如 ArrayList
。在这种情况下这不是问题,因为您知道必须从多少行和列开始 - 但值得记住。
关于java - 抛出 NullPointerException 但我不知道如何修复它。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15215481/