正在抛出NullPointerException,但我无法弄清楚如何修复它.

eld*_*222 0 java matrix nullpointerexception

我有以下代码.它是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*/ 
} 
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当代码运行时,它返回NullPointerException,并指向该行:

mainMatrix[r][c] = Float.parseFloat(raw[c]);
Run Code Online (Sandbox Code Playgroud)

如果有帮助,输出如下所示:

 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)
Run Code Online (Sandbox Code Playgroud)

2,3和]是用户输入.在"]之后按Enter键

Jon*_*eet 5

原因是你没有初始化mainMatrix.你需要这样的东西:

mainMatrix = new int[rows][columns];
Run Code Online (Sandbox Code Playgroud)

否则变量的默认值为null,所以当你尝试取消引用它(为数组的元素赋值)时,你得到了NullPointerException.

请注意,与其他一些语言不同,一旦您创建了一个数组对象,它就具有固定的大小 - 您不能仅仅在以后添加项目.为此,您需要一个List实现,如ArrayList.在这种情况下不是问题,因为你知道你必须从多少行和列开始 - 但值得记住.