0

我正在创建一个基于文本的冒险游戏,该游戏涉及多个房间、房间内的物品,以及在这些房间中来回移动。房间邻居存储在 HashMap 中,我对此完全没有经验。我有一个名为 getNeighbor 的方法,该方法旨在将房间的邻居返回到请求的方向,但我不知道该怎么做。这是代码:

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;
        }
    }
}
4

2 回答 2

0

听起来您可以将方法更改为:

public Room getNeighbor (String pDirection) {
    return myNeighbours.get(pDirection);
}

毕竟,如果无论如何都找不到密钥,Map.get()它将返回。null

于 2012-04-04T22:34:57.357 回答
0

使用HashMap.get(pDirection)

public Room getNeighbor (String pDirection){
     return myNeighbors.get(pDirection);
}

请注意,您不需要 if 语句,因为如果没有太多,则已经get()返回。null

于 2012-04-04T22:35:34.690 回答