Java run-time problem

Started by
1 comment, last by btower 15 years, 7 months ago
I am new to Java and am trying to write a simple program. The test class will instantiate an object of the "house" class which will in turn contain an array of 20 objects of the "player" class. Compiles with no errors or warnings, but gives an immediate: Exception in thread "main" java.lang.NullPointerException at test.main(test.java:6) test.java

public class test
{
        private static house h;
        public static void main(String args[])
        {
                h.players[3].setName("john");
        }
}


house.java

public class house
{
        public player[] players = new player[20];
}


player.java

public class player
{
        private static String name;

        public static void setName(String n)
        {
                name = n;
        }

}


What seems to be the problem? To my untrained eyes I can't find any errors.
http://www.sharpnova.com
Advertisement
You never actually create a house object:
public class test{        private static house h;        public static void main(String args[])        {                h = new house();                h.players[3].setName("john");        }}

Random notes:
- If you look at the stack trace the exception gave you, it would have pointed you straight to the line in question.
- If there's multiple things going on on one line which is causing a problem, then split it across multiple lines.
- Class names should start with a capital letter.
- A hardcoded number of players is probably a bad idea.
- I suspect you really don't want player.name and player.setName to be static.
I believe there is another problem in house.java:

public class house{        public player[] players = new player[20];}


Here you create an array of 20 players. But initially, the entire array contains null-references. I.e.:

players[0] = nullplayers[1] = nullplayers[2] = null...players[19] = null


You need to initialize the array with player objects. This would be a better approach:

house.java:
public class house{   public static final int MAX_PLAYERS = 20;   public player[] players;   public house()   {      players = new player[MAX_PLAYERS];      for (int i = 0; i < MAX_PLAYERS; ++i)      {         players = new player();         players.setName(i.toString()); // initialize the name to something      }   }}

This topic is closed to new replies.

Advertisement