![](/img/trans.png)
[英]Why do I get java.lang.NullPointerException at java.lang.Class.isAssignableFrom(Native Method) when calling JasperFillManager?
[英]Why do I get a java.lang.NullPointerException when I make a new Instance of a my class?
我需要创建这个类的实例,但是当我尝试时,我得到一个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();
}
}
您正在使用引用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];
您根本不初始化数组:
private int[] pointX;
private int[] pointY;
尝试访问set-method会导致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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.