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

2016/10/3

Issue with counter (nullexceptionerror)

ladamson ladamson

2016/10/3

#
Hi there Just wondering if someone can help me to debug this code. I am fairly new to this and cannot spot the error in my counter. Whenever the crab eats a wombat the counter fails to update and the game freezes with a nullexceptione error. Here is the crab code: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Crab here. * * @author (your name) * @version (a version number or a date) */ public class Crab extends Actor { /** * Act - do whatever the Crab wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move(); } public void move() { if (Greenfoot.isKeyDown("right")) { turn(5); } if (Greenfoot.isKeyDown("left")) { turn(-5); } if (Greenfoot.isKeyDown("up")) { move(2); } if (Greenfoot.isKeyDown("down")) { move(-2); } checkForWombat(); } public void checkForWombat() { Actor theWombat=getOneObjectAtOffset(0,0,Wombat.class); if (theWombat != null) { WombatWorld eatingWorld=(WombatWorld) getWorld(); eatingWorld.removeObject(theWombat); Greenfoot.playSound("slurp.wav"); bumpCounter(); } } public void bumpCounter() { WombatWorld counterWorld= (WombatWorld) getWorld(); Counter theCounter = counterWorld.getCounter(); theCounter.bumpCount(1); } } And here is the counter code: import greenfoot.*; import java.awt.Color; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Counter here. * * @author (your name) * @version (a version number or a date) */ public class Counter extends Actor { private int totalCount=0; /** * A constructor for the counter, which sets the counter's initial text image. */ public Counter() { setImage(new GreenfootImage("Wombats Eaten: " +totalCount, 20, Color.WHITE, Color.BLACK)); } /** * Increase the total amount displayed on the counter, by a given amount. */ public void bumpCount(int amount) { totalCount = totalCount+amount; setImage(new GreenfootImage("Wombats Eaten: " +totalCount, 20, Color.WHITE, Color.BLACK)); } } Many thanks in advance!
Super_Hippo Super_Hippo

2016/10/3

#
The issue is (probably) in your WombatWorld class. Please use the 'code' tags to post code.
You need to login to post a reply.