文本游戏中的空指针异常



我正在制作一款简单的文本冒险游戏。我有一个房间类和一个项目类。

每个房间都有多个项目,我试图使一个名为addItem的方法将项目存储在ArrayList中,但当我尝试添加一个项目时,我得到一个NullPointerException。

空间类

public class Room
{
    private String description;
    private HashMap<String, Room> exits;
    private ArrayList<Item>items;
    /**
     * Create a room described "description". Initially, it has
     * no exits. "description" is something like "a kitchen" or
     * "an open court yard".
     * @param description The room's description.
     */
    public Room(String description) 
    {
        this.description=description;
        exits = new HashMap<String, Room>();
        items = new ArrayList<Item>();
    }
    /**
     * Define an exit from this room.
     * @param direction The direction of the exit.
     * @param neighbor  The room to which the exit leads.
     */
    public void setExit(String direction, Room neighbor) 
    {
        exits.put(direction, neighbor);
    }
    /**
     * @return The short description of the room
     * (the one that was defined in the constructor).
     */
    public String getShortDescription()
    {
        return description;
    }
    /**
     * Return a description of the room in the form:
     *     You are in the kitchen.
     *     Exits: north west
     * @return A long description of this room
     */
    public String getLongDescription()
    {
        return "You are " + description + ".n" + getExitString();
    }
    /**
     * Return a string describing the room's exits, for example
     * "Exits: north west".
     * @return Details of the room's exits.
     */
    private String getExitString()
    {
        String returnString = "Exits:";
        Set<String> keys = exits.keySet();
        for(String exit : keys) {
            returnString += " " + exit;
        }
        return returnString;
    }
    /**
     * Return the room that is reached if we go from this room in direction
     * "direction". If there is no room in that direction, return null.
     * @param direction The exit's direction.
     * @return The room in the given direction.
     */
    public Room getExit(String direction) 
    {
        return exits.get(direction);
    }
    /**
     * adds new item to the room
     */
    public void addItem(String description)
    {
        Item Iitem = new Item(description);
        items.add(Iitem);
    }
}

项目类

public class Item
{
   private String description; 
    /**
     * Constructor for objects of class Item
     */
    public Item(String description)
    {
        this.description=description;
    }
    /**
     * gets description of the item
     */
    public String getDescription()
    {
        return description;
    }
}

您没有初始化items,所以它是null

items = new ArrayList<Item>();

我还建议您使用接口来声明,而不是特定的实现

private Map<String, Room> exits;        // stores exits of this room.
private List<Item> items;

未初始化ArrayList<Item> items

你需要做的是:

ArrayList<Item> items = new ArrayList<Item>();

最新更新