2013-03-05 33 views
0

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

回答

5

的原因是,你还没有初始化mainMatrix:当你有你的行和列变量初始化。你需要的东西,如:

mainMatrix = new int[rows][columns]; 

否则变量的null它的默认值,所以当你尝试取消对它的引用(值分配给数组的元素),你得到的NullPointerException

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

2

您尚未初始化mainMatrix属性,因此其默认值为null,因此在使用NPE时会得到NPE。

mainMatrix = new float[rows][columns]; 
+0

这是一个'float [] []',而不是'Float [] []' - 你可能会让编译器初始化所有的子阵列,按照我的答案。 – 2013-03-05 03:52:06

+0

@JonSkeet我的不好,代码固定。 – 2013-03-05 03:52:29