不知道为什么我得到这个Null指针异常错误

时间:2012-04-05 01:08:24

标签: java nullpointerexception

我正在开发一个基于文本的冒险游戏项目。它包括带有物品的房间以及从一个房间到另一个房间的导航。有一个叫做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 个答案:

答案 0 :(得分:2)

您从未初始化myNeighbors;它只是一个指向无处的参考。

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

答案 1 :(得分: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>();

答案 2 :(得分:1)

我的邻居从未被初始化。

你忘了这个:

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

问候。

答案 3 :(得分: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);
}