I created a counter, it adds the score perfectly each time it removes an enemy ship. However, I wanted to make an if statement in the spawning code of the enemy ships (Inside subclass of world), as I had failed to reference the value of 'score' into the world from the 'counter' class, I decided to int the score inside the world subclass, and then reference it inside the 'counter' class. It complied without problems, but before it even starts it throws NullPointerException:
"java.lang.NullPointerException
at Counter.<init>(Counter.java:12)
at GameWorld.<init>(GameWorld.java:13)
"
The first error which is being referenced in terminal(Line 12 = line 1 in this case):
Second reference(Line 13 = line 1 in this case):
And just in case, here is the code that is adding score to counter:
1 2 3 4 5 6 7 8 9 10 11 12 13 | int score = ((GameWorld) getWorld()).score; /** * Act - do whatever the Counter wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { setImage( new GreenfootImage( "Score : " + score, 24 , Color.WHITE, new Color( 0 , 0 , 0 , 0 ))); } public void addScore() { score++; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Counter counter = new Counter(); /** * Constructor for objects of class GameWorld. * */ public GameWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super ( 800 , 800 , 1 ); prepare(); } public Counter getCounter() { return counter; } |
1 2 3 4 5 6 7 8 9 10 11 12 | public void checkForEnemy() { if (getOneIntersectingObject(EnemyShip. class ) != null ) { getWorld().removeObject(getOneIntersectingObject(EnemyShip. class )); GameWorld gameworld = (GameWorld)getWorld(); Counter counter = gameworld.getCounter(); counter.addScore(); getWorld().removeObject( this ); } } |