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;
}
}
removeItem
method will always return null. What you probably wanted to do is something like this: { Item oldItem = item; item = null; return oldItem; }
Nate C-K 2012-04-05 01:13
You've never initialised myNeighbors
; it's just a reference that points to nowhere.
Consider private HashMap <String, Room> myNeighbors = new HashMap<String,Room>();
.
The following code is not null safe:
public void addNeighbor (String pDirection, Room r){
myNeighbors.put(pDirection, r);
}
public Room getNeighbor (String pDirection){
return myNeighbors.get(pDirection);
}
you can try:
public void addNeighbor (String pDirection, Room r){
if(myNeighbors == null) {
myNeighbors = new HashMap <String, Room>();
}
myNeighbors.put(pDirection, r);
}
public Room getNeighbor (String pDirection){
if(myNeighbors == null) {
myNeighbors = new HashMap <String, Room>();
}
return myNeighbors.get(pDirection);
}
Or
private HashMap <String, Room> myNeighbors = new HashMap <String, Room>();
myNeighors
upon construction - Oliver Charlesworth 2012-04-05 01:11
my neighbors is never initialized.
You forgot this :
private HashMap <String, Room> myNeighbors= new HashMap<String Room>();
Regards.
You have to new
the map. Change the constructor like:
public Room (String pDescription, Item pItem)
{
roomDescription = pDescription;
item = pItem;
// add this
myNeighbors = new HashMap <String, Room>();
}
and change the other constructor to:
public Room (String pDescription)
{
this(pDescription, null);
}
new
myNeighbors in the constructo - mshsayem 2012-04-05 01:10