0

我正在尝试使用 Java 制作游戏,并且在游戏中,当按下向上或向下箭头键时,被称为“Pinko”的侧向移动对象应该会发射称为“颗粒”的小物体。它成功编译并运行,但每次按向上或向下箭头键时,我都会收到一条错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Pinko.move(Pinko.java:75)
    at A2JPanel.actionPerformed(A2JPanel.java:102)
    at javax.swing.Timer.fireActionPerformed(Unknown Source)
    at javax.swing.Timer$DoPostEvent.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

有七个类:Application、Constants、JFrame、JPanel、Lovely、Pellet 和 Pinko。

我在 Pinko 类的 move 方法中的代码如下所示:

public void move(){
    area.x -= speed;
    if(area.x <= PINKO_MOVE_AREA_LHS || area.x >= PINKO_MOVE_AREA_RHS){
      speed = -speed;
    }
    if( pelletsFired > 0 ){
      for (int i = 0; i < pelletsFired; i++){
        pellets[i].move();
      }
    }
  } 

JPanel 类中的 ActionPerformed 方法如下所示:

public void actionPerformed(ActionEvent e){
    createLovely();
    if(numberOfLovelies > 0){
      for (int i = 0; i < numberOfLovelies; i++){
        lovelies[i].move();
      }
    }
    pinko.move();
    repaint();
  }

我不知道为什么我不断收到上面提到的错误。Pinko 类的 move() 方法中的 for 循环是否有问题?任何帮助都感激不尽...

4

2 回答 2

1

我敢打赌 NullPointerException 发生在这里:

pellets[i].move();

您是否尝试过验证:

  • 数组已初始化
  • 引用的索引包含我认为将是您的 Pellet 类的实例
于 2013-06-10T07:30:55.317 回答
0

如果您使用的是 IDE,请尝试使用调试器来帮助您了解代码中出了什么问题。否则,一些跟踪可以帮助您调试和确定问题:这是您可以尝试的更新代码:

public void actionPerformed(ActionEvent e){ createLovely();

 if(numberOfLovelies > 0){
  for (int i = 0; i < numberOfLovelies; i++){
    if(lovelies[i] != null )
        lovelies[i].move();
    else
        System.out.println("ERROR: Null lovelies found at an index : " + i);
  }
}
if(pinko != null)
    pinko.move();
else {
   System.out.println("OOPS pinko is null");
}

repaint();

}

于 2013-06-10T07:40:25.443 回答