Sign in to follow this  
AlphaCoder

Java run-time problem

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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] = null
players[1] = null
players[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[i] = new player();
players[i].setName(i.toString()); // initialize the name to something
}
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this