我正在开发一个基于文本的冒险游戏项目。它涉及带有物品的房间并在房间之间导航。有一个类叫做Item,这个更大的类叫做Room。我的所有方法似乎都有效,除了 addNeighbor (大概还有 getNeighbor,然后。)我创建了一个房间,里面有一个物品,效果很好,我创建了第二个房间,但是当我尝试添加一个邻居时,它崩溃并给出了我是空指针异常。我在这里做错了什么?
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;
}
}