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

2012/3/18

Why doesn't this work?

TheNightStrider TheNightStrider

2012/3/18

#
In my World, I have created a new class - Player like this:
public class Player  
{
    Player()
    {
    name="Player";
    chp=0;
    }
   String name;
        int chp;
}
Then I make an array.
Player[] save= new Player[3];
But when I try to print it out like this:
 for(int i=0;i<=2;i++){
           System.out.println(save[1].name+";"+save[1].chp);
           
           
}
I get a null pointer exception. Unless I have made a obvious error with it, I have no idea at all what is wrong Any ideas - I'd rather not make two separate arrays!
kiarocks kiarocks

2012/3/18

#
When you create an array, it does not create objects in the array. Instead, use
Player[] array = new Player[] { new Player(), new Player(), new Player()};
TheNightStrider TheNightStrider

2012/3/18

#
kiarocks wrote...
When you create an array, it does not create objects in the array. Instead, use
Player[] array = new Player[] { new Player(), new Player(), new Player()};
Right so, it is initializing the Player as null., and then a null pointer exception right. Can't believe i missed that! Thx for quick reply
You need to login to post a reply.