I'm working on creating a text-based adventure game that involves several rooms, items within rooms, and moving back and forth throughout these rooms. The room neighbors are stored within a HashMap, which I have no experience with at all. I have a method called getNeighbor that's meant to return the room's neighbor in the requested direction but I can't figure out how to do that. Here's the code:
public class Room
{
private String roomDescript;
private Item item;
private HashMap <String, Room> myNeighbors;
public Room (String pDescription){
roomDescript = pDescription;
item = null;
}
public Room (String pDescription, Item pItem){
roomDescript = pDescription;
item = pItem;
}
public String setRoomDescript(){
return this.roomDescript;
}
public String getRoomDescript(){
return this.roomDescript;
}
public Item setItem(){
return this.item;
}
public Item getItem(){
return this.item;
}
public void addItem (Item i){
i = item;
}
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){
if(myNeighbors.containsKey(pDirection)){
return ;
}else{
return null;
}
}
}
It sounds like you can just change your method to:
public Room getNeighbor (String pDirection) {
return myNeighbours.get(pDirection);
}
After all, Map.get()
will return null
if the key isn't found anyway.
public Room getNeighbor (String pDirection){
return myNeighbors.get(pDirection);
}
Note that you don't need the if-statement since get()
returns null
already if there is no much.