1

我正在开发一个基于文本的冒险游戏项目。它涉及带有物品的房间并在房间之间导航。有一个类叫做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;
    }
}
4

4 回答 4

2

你从来没有初始化过myNeighbors;它只是一个指向无处的参考。

考虑private HashMap <String, Room> myNeighbors = new HashMap<String,Room>();

于 2012-04-05T01:10:25.503 回答
1

以下代码不是空安全的:

public void addNeighbor (String pDirection, Room r){
    myNeighbors.put(pDirection, r);
}

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

你可以试试:

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

或者

private HashMap <String, Room> myNeighbors = new HashMap <String, Room>();
于 2012-04-05T01:10:57.417 回答
1

我的邻居从未初始化。

你忘了这个:

 private HashMap <String, Room> myNeighbors= new HashMap<String Room>();

问候。

于 2012-04-05T01:13:00.130 回答
1

你必须到new地图。更改构造函数,如:

public Room (String pDescription, Item pItem)
{
        roomDescription = pDescription;
        item = pItem;
        // add this
        myNeighbors = new HashMap <String, Room>();
}

并将另一个构造函数更改为:

public Room (String pDescription)
{
        this(pDescription, null);
}
于 2012-04-05T01:13:56.097 回答