为什么在创建my类的新实例时会得到java.lang.NullPointerException?
我需要创建这个类的一个实例,但是当我尝试时,会得到一个NullPointerException。 你能告诉我为什么以及如何修复吗,我在这方面还是个新手为什么在创建my类的新实例时会得到java.lang.NullPointerException?,java,Java,我需要创建这个类的一个实例,但是当我尝试时,会得到一个NullPointerException。 你能告诉我为什么以及如何修复吗,我在这方面还是个新手 public class NewTryPoints { private int[] pointX; private int[] pointY; private static final int topix = 5; public NewTryPoints(){ setX(); setY(); } public voi
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();
}
}
您根本不初始化阵列:
private int[] pointX;
private int[] pointY;
尝试访问set方法中的任何一个都会导致null,因为它们还不包含对数组对象的引用 在Java中使用数组之前,必须对其进行初始化。在构造函数中的
setX
和setY
方法中设置值之前,请初始化数组
public NewTryPoints(){
//initializing the arrays
pointX = new int[3];
pointY = new int[3];
setX();
setY();
}
希望这有帮助 在构造函数中,您正在调用
setX()
和setY()
,这反过来会用值填充数组。问题是您没有初始化这些阵列:
pointX = new int[5]; // 5 is just for the example
pointY = new int[5];
您尚未初始化对数组的引用。这意味着
private int[] pointX;
与
private int[] pointX = null;
所以当你这么做的时候
pointX[0] = ...
它抛出一个NullPointerException
您可以看到这一点的一种方法是在调试器中查看它
很可能是你打算写的
private int[] pointX = new int[3];
您正在使用引用pointX和pointY,而没有为它们分配内存,因此它们为null,并引发NullPointerException。你应该先做
public NewTryPoints(){
pointX = new int[3];
pointY = new int[3];
setX();
setY();
}
您尚未初始化数组 在调用setx和sety之前将其添加到构造函数中
pointX = new int[3];
pointY = new int[3];
您在哪一条线上获得NPE?提供跟踪!