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

2016/3/28

Returning NullPointerException

123Mike123 123Mike123

2016/3/28

#
I have several actors of the same class in the world, that are removed one at a time. This code is returning NullPointerException, despite my best efforts. Could you help me?
 public void mostraScore()
   {
       if(controlledCar != null)
       {
       List<Pontuação> listaTexto = getWorld().getObjects(Pontuação.class);
       Pontuação textoScore = listaTexto.get(0);
       textoScore.escreve("" + pontuação);
    }
    else
        carRemoved = true;
   }
danpost danpost

2016/3/28

#
I think the only place you can get a NullPointerException with the code given is in using 'getWorld'. It may be possible you are removing the actor from the world before calling the 'mostraScore' method. I am not quite sure about this, but it may be that you are not using the proper condition on line 3. Why does 'controlledCar' need to reference an actual Car object for the score text to update?
123Mike123 123Mike123

2016/3/29

#
I use the condition in line 3 so that when the car is removed, it doesn't do the next instructions. I think it returns Null because the car can be removed, wheter it is selected or not.
danpost danpost

2016/3/29

#
123Mike123 wrote...
I use the condition in line 3 so that when the car is removed, it doesn't do the next instructions. I think it returns Null because the car can be removed, wheter it is selected or not.
The 'controlledCar' field may or may not contain a Car object; and even then, it may not even be the one currently executing the code or whether it is in the world or not. The 'this' keyword refers to the object the code is being executed on and checking the value returned from the 'getWorld' method against 'null' will determine if it is in any world:
if (this.getWorld() != null)
or, since 'this' is the object of a non-static method by default:
if (getWorld() != null)
123Mike123 123Mike123

2016/3/29

#
It's working now, thanks for the help.
You need to login to post a reply.