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

2020/1/31

NullPointerException

Balu Balu

2020/1/31

#
Im doing a city builder and i get a NullPointerException when i want to add money to my bank. The counter Bank has the name Geld. I want that the objekt Wolke adds money to my bank when i press "right". Heres my World called Menue:
public class Menue extends World
{
   
    private Counter geld;
    /**
     * Constructor for objects of class Menue.
     * 
     */
    public Menue()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.

        super(1000, 750, 1); 

        menuebalken();
        Knoepfe();
        SZaehler();
        Wolke();
        //einkommen();
    }
    
    public void SZaehler() {
       Counter geld = new Counter();
        addObject(geld,250, 40);
    }
    public void Wolke() {
        Wolke wolke = new Wolke();
        addObject(wolke, 195,140);
    }
    public Counter gibgeld() {
        return geld;
    }
hers the code of the class Wolke:
public class Wolke extends Zaehler
{
   
    
    
    public void act() 
    {
        
        if (Greenfoot.isKeyDown("right")) {
           if (getWorld() !=null){
            Menue menue = (Menue)getWorld();
            
           
            menue.gibgeld().add(1);
          }
        }
        
       
    }    
Im a beginner and i looked at many other forum posts but i couldnt find anything and now the code might look messy.
danpost danpost

2020/1/31

#
Remove the first word, "Counter", from line 23 in your Menue class. Reason: you do not want to create new reference, but use the one already declared for the Menue object at line 4
Balu Balu

2020/2/4

#
I solved the problem! I changed something in the counter class and it dident work anymore, so i copy and pasted everything in to a new scenario and it worked! But thank you for your response!
You need to login to post a reply.