I am creating a Gumball machine scenario in which I have a class Inspector that picks an alien and that alien adds an object to my GumballWorld.
The code is very simple as of now but I am getting a null pointer exception. Please help!
From the console I can see that I am not able to get the world using getWorld() method.
When I directly invoke method pickRandom() from an object of RandomPicker class, it works.
But I use the object of Inspector to invoke pickAlien() method, it gives me a null pointer exception!
INSPECTOR
RANDOMPICKER
BLUEGUMBALL
public class Inspector extends Alien { /** * Act - do whatever the Inspector wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. //pickAlien(); } public void pickAlien() { int choice=Greenfoot.getRandomNumber(1); if (choice == 0) { RandomPicker RP =new RandomPicker(); RP.pickRandom(); } else { GreenPicker GP =new GreenPicker(); GP.pickGreen(); } } }
public class RandomPicker extends Picker { /** * Act - do whatever the RandomPicker wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { } public void test() { System.out.println("in test"); } public void pickRandom() { int choice = Greenfoot.getRandomNumber(1); switch(choice) { case 0: BlueGumball bg = new BlueGumball(); getWorld().addObject(bg, 366, 392); break; case 1: System.out.println("getworld()"+new RandomPicker().getWorld()); //this.getWorld().addObject(new RedGumball(), 366, 392); break; case 2: System.out.println("getworld()"+new RandomPicker().getWorld()); //this.getWorld().addObject(new GreenGumball(), 366, 392); break; } } }
*/ public class BlueGumball extends Gumball { /** * Act - do whatever the BlueGumball wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } public BlueGumball() { GreenfootImage image = getImage() ; image.scale( 50, 50 ) ; } }