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

2015/3/13

nullpointer exception array of actors

Holladerwaldelf Holladerwaldelf

2015/3/13

#
Hi guys, i have an actor-subclass called "Monster" and i'm trying to create an array of two "Monsters" in a world constructor with a reference for other classes to access. after the compilation the world constructor throws a NullPointerException when the first "Monster" should be "created". the same thing works perfectly fine with the actor-subclass "Hero", obviously i'm not using arrays correctly... probably a pretty dumb question. sorry, i'm new to java. thanks for your help!
public class HeroWorld extends World
{
    private Hero theHero;
    private Monster[] theMonsters;
    
   public HeroWorld() 
    {
        super(10, 10, 60);        
        setBackground("cell.jpg");
        setPaintOrder(Hero.class, Monster.class);
        
        theHero = new Hero();
        addObject(theHero, 0, 0); // add 1 Hero, reference theHero
        
        // add 2 Monsters, reference Monsters[0] to Monsters[1]
        theMonsters[0] = new Monster();
        theMonsters[1] = new Monster();
        addObject(theMonsters[0],2,2);
        addObject(theMonsters[1],3,3);
        
    }
davmac davmac

2015/3/13

#
You are declaring a reference to an array (line 4):
    private Monster[] theMonsters;
But, you never create the array. The reference remains null (which is why you get a NullPointerException when you try to use it). You need to set the variable to an array (use new to create the array). Something like:
    private Monster[] theMonsters = new Monster[2];
Holladerwaldelf Holladerwaldelf

2015/3/13

#
i told you it was a dumb question ;-) thanks a lot! that solved the problem.
You need to login to post a reply.