Was trying to implement a counter for the asteroid tutorial but keep getting a java.lang.NullPointerException when running the scenario, as soon as the shot hits the asteroid it throws an error, below is the code for Space, Counter and Shot.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public class Space extends World { private Counter theCounter; /** * Constructor for objects of class Space. */ public Space() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super ( 600 , 400 , 1 ); addObject( new Rocket(), 300 , 200 ); Counter theCounter = new Counter(); addObject(theCounter, 5 , 5 ); } public Counter getCounter() { return theCounter; } /** * Prepare the world for the start of the program. That is: create the initial * objects and add them to the world. */ private void prepare() { } public void act() { if (Greenfoot.getRandomNumber( 1000 ) < 3 ) { addObject( new Asteroid(), 0 , 20 ); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class Counter extends Actor { private int totalCount = 0 ; public Counter() { setImage( new GreenfootImage( "0" , 20 , Color.WHITE, Color.BLACK)); } /** * Increase the total amount displayed on the counter, by a given amount. */ public void bumpCount( int amount) { totalCount += amount; setImage( new GreenfootImage( "" + totalCount, 20 , Color.WHITE, Color.BLACK)); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | public class Shot extends Actor { private Rocket myShip; /** * Constructor for a Shot. You must specify the ship the shot comes from. */ public Shot(Rocket myShip) { this .myShip = myShip; } /** * Act - do whatever the Shot wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { int ypos = getY(); if (ypos > 0 ) { ypos = ypos - 5 ; setLocation(getX(), ypos); Actor rock = getOneIntersectingObject(Asteroid. class ); if (rock != null ) { // We've hit an asteroid! hitAnAsteroid(); getWorld().removeObject(rock); getWorld().removeObject( this ); } } else { // I reached the top of the screen getWorld().removeObject( this ); } } /** * This method gets called (from the act method, above) when the shot hits an * asteroid. It needs to do only one thing: increase the score counter. * (Everything else, such as removing the asteroid which was hit, is dealt * with in the act method). */ private void hitAnAsteroid() { Space spaceWorld = (Space) getWorld(); Counter counter = spaceWorld.getCounter(); counter.bumpCount( 5 ); //What goes here???? // We want to call the "bumpCount" method from the Counter class - // but how??!! } } |