【问题标题】:nullPointerException error greenfootnullPointerException 错误绿脚
【发布时间】:2015-01-28 15:20:28
【问题描述】:

我正在做一个关于编程课程介绍的项目,但遇到了一个小问题。我们正在制作一个横向卷轴,我现在正在做计分器。我的问题是,当我尝试在 act 方法(每帧调用一次)之外的任何方法中创建对计数器类的引用时,我得到一个空指针异常错误。如果你想看看,你可以下载包含我的代码的压缩文件here

编辑: 这是有问题的代码:

public class HeroMissile extends Missiles

{

/**
 * Act - do whatever the HeroMissile wants to do. This method is called whenever
 * the 'Act' or 'Run' button gets pressed in the environment.
 */
public void act() 
{
    move(8);
    remove();
}    

public void remove() {
    if(isTouching(Drone.class)) {
        removeTouching(Drone.class);
        getWorld().addObject(new Explosion(), getX(), getY());
        getWorld().removeObject(this);
        addScore();
        return;
    }
}

public void addScore() {
    City cityWorld = (City) getWorld();
    **Counter scoreCounter = cityWorld.getCounter();**
    scoreCounter.add(1);
}

}

【问题讨论】:

    标签: nullpointerexception greenfoot


    【解决方案1】:

    在您将自己从世界上移除后,您正在调用getWorld() [in addScore()]。在这种情况下,getWorld() 将返回 null,因此您将得到一个空指针异常。尝试更改remove() 中的顺序以添加分数,然后再将自己从世界上移除。

    【讨论】:

      猜你喜欢
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      相关资源
      最近更新 更多