【问题标题】:Unexpected NullPointerException assigning arrays from constructor从构造函数分配数组时出现意外的 NullPointerException
【发布时间】:2012-05-09 16:15:48
【问题描述】:

我似乎无法弄清楚这一点,如果你们能帮助我,那就太棒了! 我正在尝试将已创建的对象传递给构造函数,以便获取它们的所有值。

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 都是数组。

提前感谢您!

【问题讨论】:

    标签: java android arrays nullpointerexception


    【解决方案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

    【讨论】:

    • 非常感谢,成功了。这很有趣,因为我知道这一点并且正在搞砸它,但惨遭失败并将它们置于该死的循环中!编辑:是的 maxAliens 和 maxShots 在 MainGamePanel 中初始化时实际上是在声明其他对象数组大小。
    【解决方案2】:

    您可以将bulk 和alienT 参数分别定义为Collection&lt;Bullet&gt;Collection&lt;AllienT&gt;

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

    【讨论】:

    • 这让我有点过头了哈哈,我对 java 和一般编程还是很陌生,不过学得很快。我假设的集合是另一种只使用从构造函数调用的数组而不创建新数组的方法?是否可以在同一个类的其他方法中使用?
    • Collection 是一个由许多数据结构类实现的接口,如 ArrayList、HashSet、LinkedHashSet、TreeSet... 您可以将参数定义为集合,并且可以使用您为每种情况决定的实现。这是一些文档:[链接]docs.oracle.com/javase/6/docs/api/java/util/Collection.html
    【解决方案3】:

    由于aliensbullet 成员数组是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];
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-17
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多