What can I return in this if statement?

Go To StackoverFlow.com

0

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;
        }
    }
}
2012-04-04 22:33
by Michael Moore


0

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.

2012-04-04 22:34
by Jon Skeet


0

Use HashMap.get(pDirection):

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.

2012-04-04 22:35
by amit
Thanks to both of you! This worked like a charm - Michael Moore 2012-04-04 23:43
@MichaelMoore: You are welcome. Don't forget to accept the answer you found most helpful to you - amit 2012-04-05 06:13
Ads