I’m working on a text-based adventure game project. It involves rooms with items in them and navigating from room to room. There’s a class called Item and this larger class called Room. All of my methods seem to work except addNeighbor (and presumably getNeighbor too, then.) I created a room with an item and that worked just fine, and I created a second room, but when I tried to add a neighbor it crashed and gave me a Null Pointer Exception. What am I doing wrong here?
public class Room
{
private String roomDescription;
private Item item;
private HashMap <String, Room> myNeighbors;
public Room (String pDescription){
roomDescription = pDescription;
item = null;
}
public Room (String pDescription, Item pItem){
roomDescription = pDescription;
item = pItem;
}
public String getRoomDescription(){
return roomDescription;
}
public Item getItem(){
return item;
}
public void addItem (Item i){
item = i;
}
public boolean hasItem(){
if(item != null){
return true;
}else{
return false;
}
}
public void addNeighbor (String pDirection, Room r){
myNeighbors.put(pDirection, r);
}
public Room getNeighbor (String pDirection){
return myNeighbors.get(pDirection);
}
public Item removeItem(){
item = null;
return item;
}
public String getLongDescription(){
String longDescription = "You are at " + roomDescription + "You see " + item;
return longDescription;
}
}
You’ve never initialised
myNeighbors; it’s just a reference that points to nowhere.Consider
private HashMap <String, Room> myNeighbors = new HashMap<String,Room>();.