Jump to content
  • Advertisement
Sign in to follow this  
AlphaCoder

Java run-time problem

This topic is 3562 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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.

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 = new player();
players.setName(i.toString()); // initialize the name to something
}
}
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!