当我创建一个新类的实例时,为什么会出现java.lang.NullPointerException?

时间:2014-02-23 13:23:49

标签: java

我需要创建这个类的实例,但是当我尝试时,我得到一个NullPointerException。 你能告诉我为什么以及如何解决这个问题,我对此仍然很陌生。

public class NewTryPoints {

private int[] pointX;
private int[] pointY;
private static final int topix = 5;

public NewTryPoints(){
    setX();
    setY();
    }

public void setX(){

    pointX[0] = 1;
    pointX[1] = (int)Math.random() * ( 50 - 1 ) * topix;
    pointX[2] = 2 + (int)(Math.random() * ((50 - 2) + 1)) * topix;
};

public void setY(){

    pointY[0] = 1 * topix;
    pointY[1] = 2 + (int)(Math.random() * ((50 - 2) + 1)) * topix;
    pointY[2] = 1 * topix;

};

public int[] getpointX() { return pointX; };
public int[] getpointY() { return pointY; };

}

其他课程

public class Main {

public static void main(String[] args) {
NewTryPoints points = new NewTryPoints();   

  }

}

6 个答案:

答案 0 :(得分:1)

您使用引用 pointX pointY 而未分配内存,因此它们为null并引发NullPointerException。你应该先做..

public NewTryPoints(){
    pointX = new int[3];
    pointY = new int[3];
    setX();
    setY();
}

答案 1 :(得分:1)

您尚未初始化阵列。

在调用setx和sety之前在构造函数中添加它。

pointX = new int[3];
pointY = new int[3];

答案 2 :(得分:0)

您根本不初始化数组:

private int[] pointX;
private int[] pointY;

尝试访问set-method中的任何一个导致null,因为它们还没有包含对数组对象的引用!

答案 3 :(得分:0)

在Java中使用它之前,必须先初始化数组。在构造函数中的setXsetY方法中设置值之前,请初始化数组

public NewTryPoints(){
    //initializing the arrays
    pointX = new int[3]; 
    pointY = new int[3];
    setX();
    setY();
    }

希望这有帮助!

答案 4 :(得分:0)

在您的构造函数中,您调用setX()setY(),然后使用值填充数组。问题是你没有初始化这些数组:

pointX = new int[5]; // 5 is just for the example
pointY = new int[5];

答案 5 :(得分:0)

您尚未初始化对数组的引用。这意味着

private int[] pointX;

相同
private int[] pointX = null;

所以当你这样做时

pointX[0] = ...

抛出NullPointerException。

您可以通过在调试器中查看此内容来看到这一点。

很可能你打算写

private int[] pointX = new int[3];
相关问题