This site requires JavaScript, please enable it in your browser!
Greenfoot back
ftelliott
ftelliott wrote ...

2016/12/13

Null Exception Pointer in Tutorial #6

ftelliott ftelliott

2016/12/13

#
We are trying to implement the Counter actor in Tutorial #6. When we get to the point in our game where we want to bump the score, we trap to a NullPointerException. We understand this means our instance pointer isn't working but we're not sure why. In our World subclass, called "MyWorld" we have:
public class MyWorld extends World
{
  private Counter theCounter;
  public MyWorld()
  {
    super(1150,600,1);
    prepare();
  }

  public Counter getCounter()
  {
    return theCounter;
  }

  private void prepare()
  {
    Counter theCounter = new Counter();
    addObject(theCounter, 61,63);
  }
}
In our Counter class, we have:
public class Counter extends Actor
{
  int score = 0;
  public void addScore()
  {
    score =score +1;
  }

  public void act()
  {
    setImage(new GreenfootImage("Score :",score);
  }
}
and in our shooting object's act loop, when it touches the "enemy" we have:
  MyWorld = theWorld =(MyWorld) getWorld();
  Counter theCounter = theWorld.getCounter();
  theCounter.addScore();
danpost danpost

2016/12/13

#
The 'theCounter' field in the MyWorld object is 'null'. Nothing is ever assigned to it. You might think that line 17 of the MyWorld class code does that; but in reality, it creates a local variable with the same name as the instance field. Remove 'Counter' from the beginning of line 17 so that 'theCounter' will refer to the instance field already declared.
You need to login to post a reply.