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

2013/12/17

NullPointerException using setLocation()

NullPointer NullPointer

2013/12/17

#
Hi, i need help with a NullPointerException. Here is the errorcode: java.lang.NullPointerException at Playfield.Start(Playfield.java:356) at Playfield.Game(Playfield.java:328) at Playfield.act(Playfield.java:316) And here is the code that I think is important for the error:
public class Playfield extends World
{
private StoneGreen1 G1;
...
public void prepare()
    {      
...
 StoneGreen1 G1 = new StoneGreen1();
       addObject(G1, 0, 0);
...
}
 public void Start()
  {  
                     ...
                     case 1:
                            System.out.println("1");
                            G1.setLocation(0,4);
                            break;
                            ...
The error code is referencing to the line "G1.setLocation". Thanks in advance for any advice
SPower SPower

2013/12/17

#
Make sure you call prepare before you call Start: if you didn't call prepare first, then G1 will be null in Start. Btw, some advice to improve your programming: instance variables like your G1 should start with a lowercase, so g1 instead of G1. Also, method names should start with a lowercase, so your method Start should be start. Java won't complain about this, but it confuses people when you do it wrong.
davmac davmac

2013/12/17

#
In your prepare method:
 StoneGreen1 G1 = new StoneGreen1();  
You're creating a new local variable called G1 rather than setting the value of the existing G1 field. Change it to:
G1 = new StoneGreen1();  
NullPointer NullPointer

2013/12/17

#
Thanks davmac! Everything is working fine now. And thank you SPower too, I even knew about those "rules" but simply forgot to do it like this. Thanks guys.
You need to login to post a reply.