有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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都是阵列

提前谢谢你


共 (3) 个答案

  1. # 1 楼答案

    您需要初始化阵列:

    Bullet[] bullet;
    Aliens[] aliens;
    

    例如:

    public Drops(Ship ship,Bullet[] bull,Aliens[] alienT){
        this.ship = ship;
        this.bullet = new Bullet[bull.length];
        this.aliens = new Aliens[alianT.length];
        // ..
    

    此外,确保循环条件考虑了alienTbull的长度,如果它们比MainGamePanel.maxAliensMainGamePanel.maxShots短,则会得到ArrayIndexOutOfBoundsException

  2. # 2 楼答案

    你得到NPE是因为aliensbullet成员数组是null。确保在构造函数中以适当的长度实例化它们:

    public Drops(Ship ship,Bullet[] bull,Aliens[] alienT){
        this.ship = ship;
        this.aliens = new Aliens[alienT.length];
        this.bullet = new Bullet[bull.length];
        // ...
    }
    
  3. # 3 楼答案

    您可以将bull和allienT参数分别定义为Collection<Bullet>Collection<AllienT>

    然后,您可以通过ArrayListHashSet或您喜欢的集合类调用此方法