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

2016/6/24

java.lang.NullPointerException

James-S James-S

2016/6/24

#
I keep getting a java.lang.NullPointerException when adding points
java.lang.NullPointerException
	at Points.changeCounter(Points.java:23)
	at PurchaseI1.purchase(PurchaseI1.java:31)
	at PurchaseI1.act(PurchaseI1.java:22)
	at greenfoot.core.Simulation.actActor(Simulation.java:594)
	at greenfoot.core.Simulation.runOneLoop(Simulation.java:552)
	at greenfoot.core.Simulation.runContent(Simulation.java:215)
	at greenfoot.core.Simulation.run(Simulation.java:205)
The lines from this i have put in italics I have a shop, and i need to add points to buy an item. This is the code i use to access the points from different actors, this is in MyWorld
public int counter = 0;
Points points = new Points(); 
private int time = 3600;
    

 public Points getPoints()
    {
         return points;
    }
This is the code that i use to Display the points and change the points
    public void act() 
    {
        setImage(new GreenfootImage("Points: " + ((MyWorld)getWorld()).counter, 24, Color.BLACK, new Color(0, 0, 0, 0)));
    } 

    public void changeCounter(int amount)
    {
        [i]((MyWorld)getWorld()).counter = ((MyWorld)getWorld()).counter + amount;[/i]
    }
    
This is the code that should deduct from the points, this is in an actor called PurchaseI1
    public void act()
    {
        [i]purchase();[/i]
    }

    public void purchase()
    {
        if(((MyWorld)getWorld()).counter >= 2 )
        {
            MyWorld world = (MyWorld)getWorld();
            Points points = world.getPoints();
[i]            points.changeCounter(-2);[/i]
        }
    }
    
Please help, this is for a school assignment and i would like to get the shop working so i can add it to my game
Super_Hippo Super_Hippo

2016/6/24

#
Do you add the Point object into your world? You created it with this line:
Points points = new Points();
'getWorld' returns null on this object if it isn't in the world (so either not added at all or removed). To add it, you can use this line:
addObject(points, 50, 50); //change the numbers as you wish
You need to login to post a reply.