Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why am I getting NullPointerException?

 
Paul Carter
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't know why but I'm getting runtime error:
"java.lang.NullPointerException"
when I add the lines
players[4].gold = 0; //Dragon!!!
players[4].warriors = 0; //Dragon!!!
Anyone know why?

I changed the scope of the variables from private to public but it didn't make any difference.

Thanks in advance

Paul.

public class TowerCode {

/** Creates a new instance of TowerCode */
public TowerCode() {
}

public void SetUpGame() {
System.out.println("Set Tower Startup Values");

//Set Array of 5 Players (Player 4 = Dragon)
Player players[];
players = new Player[5];

players[4].gold = 0; //Dragon!!!
players[4].warriors = 0; //Dragon!!!
}

public class Player {
private int gold = 30;
private int warriors = 10;
private int food = 25;

private int[] boughtItems = null;
private int[] foundItems = null;

private int kingdom = 0;
private int moves = 0;
private int lastLocation = 0;
private boolean cursed = false;
}
}
 
Tim LeMaster
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have created an array that holds five references to player objects, but you haven't created any Player objects for them to reference. So players[4] is a reference to a player object but its value is currently null.

You need to do something like

 
fred rosenberger
lowercase baba
Bartender
Posts: 12146
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you're making a common mistake.

when you write

Player players[];
players = new Player[5];

you have created an array that will hold players, but you have not actually created the players.

the line

players[4].gold = 0;

says "take the thing i put in slot 4 and do stuff to it" - but there is nothing there yet. you need something like

for (int x = 0; x<numPlayers; x++)
{
players[x] = new Player();
}
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

When you create a Java array of some kind of object, what you get is an array of references to objects. All of those references are null. You can't use the objects in the array, because there are no objects in the array. You need to put objects in there first -- i.e.,

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Synchronized posting!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic