java意外的NullPointerException从构造函数分配数组
我似乎不明白,如果你们能帮我,那就太棒了! 我试图将已经生成的对象传递到构造函数中,以便获得它们的所有值
public class Drops {
Ship ship;
Bullet[] bullet;
Aliens[] aliens;
Movement movement;
public Drops(Ship ship,Bullet[] bull,Aliens[] alienT) {
this.ship = ship;
for (int a = 0; a < MainGamePanel.maxAliens;a++) {
System.out.println(a +" " +alienT[a].x); // THIS WORKS, when nothing
// is being assigned, so the values
// are being passed correctly.
this.aliens[a] = alienT[a];
for (int b = 0; b < MainGamePanel.maxShots;b++){
this.bullet[b] = bull[b];
}
}
}
// that is is the class, and also where the error occurs
大体上,我是这样将值发送给构造函数的
drop = new Drops(ship, bull, alienT);
ship不是阵列bull和alienT都是阵列
提前谢谢你
# 1 楼答案
您需要初始化阵列:
例如:
此外,确保循环条件考虑了
alienT
和bull
的长度,如果它们比MainGamePanel.maxAliens
和MainGamePanel.maxShots
短,则会得到ArrayIndexOutOfBoundsException
# 2 楼答案
你得到NPE是因为
aliens
和bullet
成员数组是null
。确保在构造函数中以适当的长度实例化它们:# 3 楼答案
您可以将bull和allienT参数分别定义为
Collection<Bullet>
和Collection<AllienT>
然后,您可以通过
ArrayList
、HashSet
或您喜欢的集合类调用此方法