我似乎无法弄清楚这一点,如果你们能帮助我,那将是非常棒的! 我试图将已经创建的对象传递给构造函数,这样我就可以得到它们的所有值。
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
在main中我将值发送到构造函数,如此
drop = new Drops(ship, bull, alienT);
ship不是数组bull,alienT都是数组。
提前谢谢!
答案 0 :(得分:1)
您需要初始化数组:
Bullet[] bullet;
Aliens[] aliens;
e.g:
public Drops(Ship ship,Bullet[] bull,Aliens[] alienT){
this.ship = ship;
this.bullet = new Bullet[bull.length];
this.aliens = new Aliens[alianT.length];
// ..
此外,请确保循环条件考虑alienT
和bull
的长度,如果它们短于MainGamePanel.maxAliens
且MainGamePanel.maxShots
您将获得ArrayIndexOutOfBoundsException
{1}}。
答案 1 :(得分:0)
您可以将bull和allienT参数分别定义为Collection<Bullet>
和Collection<AllienT>
。
然后,您可以调用此方法传递ArrayList
,HashSet
或您首选的集合类。
答案 2 :(得分:0)
由于aliens
和bullet
成员数组为null
,因此您获得了NPE。确保你在构造函数中以适当的长度实例化它们:
public Drops(Ship ship,Bullet[] bull,Aliens[] alienT){
this.ship = ship;
this.aliens = new Aliens[alienT.length];
this.bullet = new Bullet[bull.length];
// ...
}