0

I get a null pointer exception when a call a method on a custom class. When i call my Map constructor on my driver i get a NPE error. I initialize my 2D array field in Map.java

public class Map {
private Field[][] gameMap;
private int row, col;
private int rowPlayer, colPlayer;
 public Map(){
     gameMap = new Field[10][20];
     rowPlayer = 0;
     colPlayer = 0;
     gameMap[rowPlayer][colPlayer].setPlayerLoc(); //NPE happens here
 }
 }

Here is Field.java

public class Field {
private int playerLoc;
private char fieldType;
private int plantedDay, readyDay;
private char typeOfCrop;
public Field(){
    fieldType = 'u';
    playerLoc = 0;
    plantedDay = 0;
}
public void setFieldUntilled(){
    fieldType = 'u';
}
public void setFieldTilled(){
    fieldType = 't';
}
public void setPlayerLoc(){
    playerLoc = 1;
}
public void removePlayerLoc(){
    playerLoc = 0;
}
public int getPlayerLoc(){
    return playerLoc;
}
public void setPlantDay(int Day){
    plantedDay = Day;
}
public void setReadyDay(int x){
    readyDay = x;
}
}

I would like to know how to fix it and why the NPE happens. Thank you!

2 Answers2

2

You have to initialize gameMap[rowPlayer][colPlayer], since it contains null :

 public Map(){
     gameMap = new Field[10][20];
     rowPlayer = 0;
     colPlayer = 0;
     gameMap[rowPlayer][colPlayer] = new Field();
     gameMap[rowPlayer][colPlayer].setPlayerLoc();
 }
Eran
  • 387,369
  • 54
  • 702
  • 768
2

Same old newbie array problem that we see N times a day:

You create a 2-D array populated with nulls.

   gameMap = new Field[10][20];

You fetch a value (null of course)` from the array and try to access a field.

   gameMap[rowPlayer][colPlayer].setPlayerLoc();

It fails because you can't access a field of null. NullPointerException ensues.

Solution: you need to create and assign new Field instances to each of the array cells.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216