Java 向Hashmap添加项并获取错误null.pointer.exception

Java 向Hashmap添加项并获取错误null.pointer.exception,java,arraylist,hashmap,Java,Arraylist,Hashmap,第一部分是我的游戏类,游戏类负责跟踪玩家的物品和当前位置。第二部分是my room类,实现一个类来维护关于房间的信息,包括:房间字符串的描述、项目项和所有相邻房间的列表HashMap 当我运行main方法来测试这些方法时,我调用的每个方法都会得到null.pointer.exception。由于某些原因,我不知道为什么在运行调试器时每个变量都设置为null,所以我假设这就是为什么我会出现错误。任何关于我如何解决这个问题的帮助,或者如果我做错了什么,请提供帮助。这也是我编程的第一学期,所以我是一个

第一部分是我的游戏类,游戏类负责跟踪玩家的物品和当前位置。第二部分是my room类,实现一个类来维护关于房间的信息,包括:房间字符串的描述、项目项和所有相邻房间的列表HashMap

当我运行main方法来测试这些方法时,我调用的每个方法都会得到null.pointer.exception。由于某些原因,我不知道为什么在运行调试器时每个变量都设置为null,所以我假设这就是为什么我会出现错误。任何关于我如何解决这个问题的帮助,或者如果我做错了什么,请提供帮助。这也是我编程的第一学期,所以我是一个半初学者

******************更新************
好吧,我改变了我的构造函数,它似乎已经解决了这个问题?现在我仍然在这里得到相同的错误myNeighbor.putpDirection,r;这是在public void addNeighborString pddirection中,我的房间类中的房间r原始帖子的第二部分尝试调试代码。在eclipse中,您还可以添加NullPointerExeption作为断点和调试

将代码封装在try-and-catch块中,这样您就可以找到在哪一行获得异常

import java.util.ArrayList;
import java.util.HashMap;
/**
 * Write a description of class Game here.
 * 
 * @author (Christopher ) 
 * @version (a version number or a date)
 */
public class Game
{
    ArrayList <Item> myArray;
    HashMap <String, Room> myNeighbor;
    Room currentRoom;
    String currentMessage;
    Room hallway, kitchen, bathroom, livingRoom, upstairsLobby, blakesRoom, jaysRoom, mikesRoom;
    Item crumbs, eggs, cellPhone, textBooks, poptarts, pizzaRolls, clothes, chips; 
    public Game()
    {
        ArrayList <Item> myArray = new ArrayList();
        currentRoom = hallway;
    }

    private void createRooms()
    {
        myNeighbor = new HashMap <String, Room> ();

        crumbs = new Item("Crumbs", "small crumbs of some kind of food", 100);
        eggs = new Item("Raw Eggs", "a couple of raw eggs still contained within their egg shells", 1100);
        cellPhone = new Item("Cell Phone", "Mike's cell phone he must have forgotten here...", 0);
        textBooks = new Item("Textbooks", "Jay's textbooks, because he can't use his bedroom to store his stuff", 0);
        poptarts = new Item("Pop Tarts", "an un-opened box of chocolate pop tarts that someone must have left behind...", 1500);
        pizzaRolls = new Item("Pizza Rolls", "cooked steaming pizza rolls piled high", 2000);
        clothes = new Item("Clothes", "clothes, a lot of clothes all over the floor and all over the room, who knows if they're clean or not...", 0);
        //        miningTools = new Item("Mining Tools", "pickaxes, drills, and everything else you need to extract rocks and minerals from the earth's crust", 100);
        chips = new Item("Chips", "chip bag hidden away that is only half full now", 400);

        hallway = new Room("in a dark hallway with crumbs scattered over the ground", crumbs);
        kitchen = new Room("in a kitchen with raw eggs lying on the counter tops", eggs);
        bathroom = new Room("in a bathroom with a stand up shower, a washer, a drier, and Mike's cell phone left behind laying on the counter", cellPhone);
        livingRoom = new Room("in a living room with Jay's textbooks all over the room", textBooks);
        upstairsLobby = new Room("in a lobby at the top of the stairs with a box of pop tarts on the ground", poptarts);
        blakesRoom = new Room("in a dark room with towers of pizza rolls covering the desk and scattered across the bed", pizzaRolls);
        jaysRoom = new Room("in a cluttered room with clothes covering every inch of the floor and nothing hanging on the walls", clothes);
        mikesRoom = new Room("in a bed room with mining tools and a bag of chips hidden underneath a pillow on the bed", chips);

        hallway.addNeighbor("north", kitchen);
        hallway.addNeighbor("west", upstairsLobby);
        hallway.addNeighbor("east", livingRoom);
        kitchen.addNeighbor("west", bathroom);
        kitchen.addNeighbor("south", hallway);
        bathroom.addNeighbor("east", kitchen);
        livingRoom.addNeighbor("west", hallway);
        upstairsLobby.addNeighbor("north", jaysRoom);
        upstairsLobby.addNeighbor("west", blakesRoom);
        upstairsLobby.addNeighbor("east", mikesRoom);
        upstairsLobby.addNeighbor("south", hallway);
        blakesRoom.addNeighbor("east", upstairsLobby);
        jaysRoom.addNeighbor("south", upstairsLobby);
        mikesRoom.addNeighbor("west", upstairsLobby);

    }

    private void setWelcomeMessage()
    {
        currentMessage = "You are locked inside of a campus view apartment.  The goal of this game is to eat 5000 calories to maximize gains so you can leave.  You will have to navigate around the apartment searching for food and eating it to obtain your calorie goal.";
    }

    public String getMessage()
    {
        return currentMessage;
    }

    public void help()
    {
        String message1 = "If you are short on calories, be sure to check the bedrooms";
        String message2 = "Don't forget to go upstairs";
        String reminder = "Remember the goal of the game to get 5000 calories";
    }

    public void look()
    {
        currentMessage = currentRoom.getLongDescription();
    }

    public void move(String direction)
    {
        String msg;

       Room nextRoom = currentRoom.getNeighbor(direction);
        if (nextRoom == null){
            msg = "You can't go in that direction";
        }
        else{
            currentRoom = nextRoom;
            msg = currentRoom.getLongDescription();
        }
    }
    // 
    //     public boolean gameOver()
    //     {
    //         int count = 0;
    // 
    //         for(int i = 0; i < myArray.size(); i++ ){
    //             count += myArray.indexOf(i).getCalories(;
    //         }
    //         if(count == 5000){
    //             currentMessage = "You have won!";
    //             return true;
    //         }
    //         else{
    //             return false;
    //         }
    //     }

    public void take()
    {      

        if(currentRoom.hasItem() == false){
            currentMessage = "there is not an item in the room to take";
        }
        else if(currentRoom.getItem().getCalories() > 100){
            currentMessage = "there is not enough calories in here for you to increase gains";
        }
        else{
            currentRoom.addItem(currentRoom.getItem());
            currentMessage = "you are now holding the item";
        }
    }

    private Item checkForItem(String name)
    {

        for(int i = 0; i < myArray.size(); i++ ){
            if(i + "" == name){
                return currentRoom.getItem();
            }            
        }
        return null;
    }

    public void drop(String name)
    {      

        for(int i = 0; i < myArray.size(); i++ ){
            Item temp = myArray.remove(i);
            if(i + "" == name  && currentRoom.hasItem() == false){
                myArray.remove(i);
                currentRoom.addItem(temp);
                currentMessage = "you have successfully dropped the item in the room";
            }
            else if(currentRoom.hasItem() == true)
            {
                currentMessage = "the room already has an item";
            }
            else if(i +"" != name)
            {
                currentMessage = "you are not holding that item";
            }
        }
    }

    public void show()
    {
        if(myArray.size() > 0){
            currentMessage = "" + myArray;
        }
    }

    public static void main(String ar
        System.out.println(g.getMessage());
        g.move("west");
        System.out.println(g.getMessage());
        g.take();
        System.out.println(g.getMessage());
        g.move("west");
        System.out.println(g.getMessage());
        g.move("east");
        System.out.println(g.getMessage());
        g.move("south");
        System.out.println(g.getMessage());
        g.move("west");
        System.out.println(g.getMessage());
    }
}

**************************************************************************************************
import java.util.HashMap;
/**
 * Write a description of class Room here.
 * 
 * @author (Christopher Saikalis) 
 * @version (a version number or a date)
 */
public class Room
{
    private String description;
    private Item item;
    private HashMap <String, Room> myNeighbor;

    public Room (String pDescription)
    {
        description = pDescription;
        item = null;
        HashMap <String, Room> myNeighbor = new HashMap <String, Room> ();
    }

    public Room (String pDescription, Item pItem)
    {
        description = pDescription;
        item = pItem;
    }

    public String getDescription()
    {
        return description;
    }

    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)
    {
        myNeighbor.put(pDirection, r);   
    }

    public Room getNeighbor(String pDirection)
    {
        Room next = myNeighbor.get(pDirection);
        return next;
         if(next != null){
             return next;
         }
         else{
             return null;
         }
    }

    public Item removeItem()
    {
        Item temp;
        temp = item;
        item = null;
        return temp;
    }

    public String getLongDescription()
    {
        String part1 = "You are " + description;
        String part2 = "You see ";
        if(item != null){
            return part1 + "" + part2 + "" + item.getDescription() + "" + item.getCalories();
        }
        return part1;
    }
}
并将堆栈跟踪粘贴到问题中

编辑:

由于createRooms是私有方法,因此必须从类方法或构造函数调用它

public static void main(String ar[]) {
    try {
        System.out.println(g.getMessage());
        g.move("west");
        System.out.println(g.getMessage());
        g.take();
        System.out.println(g.getMessage());
        g.move("west");
        System.out.println(g.getMessage());
        g.move("east");
        System.out.println(g.getMessage());
        g.move("south");
        System.out.println(g.getMessage());
        g.move("west");
        System.out.println(g.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

你确定这是你运行的代码吗?? 首先看看你的主要方法

public void move(String direction)
{
    Room nextRoom = currentRoom.getNeighbor(direction);
    if (nextRoom == null){
        currentMessage = "You can't go in that direction";
    }
    else{
        currentRoom = nextRoom;
        currentMessage = currentRoom.getLongDescription();
    }
}
根据您的代码片段,您将得到编译时错误 加上无法访问的代码

**************************编辑****************************

像这样更改构造函数

  public static void main(String ar
        System.out.println(g.getMessage());
        g.move("west");
        System.out.println(g.getMessage());
        g.take();
        System.out.println(g.getMessage());
        g.move("west");
        System.out.println(g.getMessage());
        g.move("east");
        System.out.println(g.getMessage());
        g.move("south");
        System.out.println(g.getMessage());
        g.move("west");
        System.out.println(g.getMessage());
    }

在Java中,默认情况下,类的所有实例变量都分配给null

因此,在游戏类中,实例变量声明如下:

  public Game()
    {
        ArrayList <Item> myArray = new ArrayList();
        createRooms();
        currentRoom = hallway;
    }
public class Game
{
    ....
    Room currentRoom;
    String currentMessage;
    ....
}
public void move(String direction)
{
   Room nextRoom = currentRoom.getNeighbor(direction);
   ...
} 
public Game()
    {
        createRooms();
        myArray = new ArrayList();
        currentRoom = hallway;
    }
public Room(String pDescription, Item pItem) {
        description = pDescription;
        item = pItem;
        myNeighbor = new HashMap <String, Room> ();
    } 
很明显,变量没有任何对象,所以它们是空的

现在从您的主要方法开始,您可以这样做:

  public Game()
    {
        ArrayList <Item> myArray = new ArrayList();
        createRooms();
        currentRoom = hallway;
    }
public class Game
{
    ....
    Room currentRoom;
    String currentMessage;
    ....
}
public void move(String direction)
{
   Room nextRoom = currentRoom.getNeighbor(direction);
   ...
} 
public Game()
    {
        createRooms();
        myArray = new ArrayList();
        currentRoom = hallway;
    }
public Room(String pDescription, Item pItem) {
        description = pDescription;
        item = pItem;
        myNeighbor = new HashMap <String, Room> ();
    } 
来到一线游戏g=新游戏;此处Java调用构造函数,因此代码为:

public static void main(String args[]){
    Game g = new Game();
    System.out.println(g.getMessage());
    g.move("west");
    ....
}
在这里,您试图访问变量currentRoom而不初始化它,因此它仍然是null对象,因此您得到java.lang.NullPointerException

更新:

因此,如下更改代码:

  public Game()
    {
        ArrayList <Item> myArray = new ArrayList();
        createRooms();
        currentRoom = hallway;
    }
public class Game
{
    ....
    Room currentRoom;
    String currentMessage;
    ....
}
public void move(String direction)
{
   Room nextRoom = currentRoom.getNeighbor(direction);
   ...
} 
public Game()
    {
        createRooms();
        myArray = new ArrayList();
        currentRoom = hallway;
    }
public Room(String pDescription, Item pItem) {
        description = pDescription;
        item = pItem;
        myNeighbor = new HashMap <String, Room> ();
    } 
在上面的代码中,您可以看到现在我们正在调用createRooms,并且myArray已正确初始化,而不是创建新变量

您还需要初始化Room类的myNeighbor变量,如下所示:

  public Game()
    {
        ArrayList <Item> myArray = new ArrayList();
        createRooms();
        currentRoom = hallway;
    }
public class Game
{
    ....
    Room currentRoom;
    String currentMessage;
    ....
}
public void move(String direction)
{
   Room nextRoom = currentRoom.getNeighbor(direction);
   ...
} 
public Game()
    {
        createRooms();
        myArray = new ArrayList();
        currentRoom = hallway;
    }
public Room(String pDescription, Item pItem) {
        description = pDescription;
        item = pItem;
        myNeighbor = new HashMap <String, Room> ();
    } 

我已删除msg局部变量,并在此处使用currentMessage实例变量。

因为myNeighbor是一个hashMap,您知道不能有多个北/南/东/西键吗?我在Room nextRoom=currentRoom.getNeighbordirection收到错误@Pier AlexandreBouchard什么意思我不能有多个北/南/东/西钥匙?在createRooms中。例如,您尝试添加至少两个带有西键走廊的房间。addNeighborwest,UpstairsRobble;厨房,西大街,浴室。Hashmap只允许一个west键。可能重复Yes这是我运行的主要方法,它符合要求,但当我运行它时,当我第一次尝试移动时,我立即得到错误。变量g的初始化部分在哪里。??你不应该关闭像publicstaticvoidmainstring这样的主方法吗{**code**}哦,哇,我不知道为什么它没有正确地复制和粘贴,但是是的,我使用的代码是:publicstaticvoidmainstring args[]{Game g=new Game;System.out.printlng.getMessage;那么剩下的就是sameI了。我想如果你已经正确初始化了所有东西,那么走廊的初始化部分在哪里呢?我想currentRoom是空的。首先调用createRooms方法,然后再试一次。或者在构造函数中调用createRooms作为第一个语句。我把它放在在move方法中,当我运行main方法时,在第一次movewest之后,main方法的其余部分被注释掉,它仍然在蓝色J终端窗口中返回null,它显示的是null.ok。你的main方法中的g是什么?调用一个新游戏。从我的公共游戏方法。看看更新的游戏构造函数和move方法。是的,但在publ中ic游戏我继续初始化这些实例variables@Christopher,添加了清晰的解释以显示变量为空的原因,请检查。好的,我正在关注您,现在对我来说很有意义,我需要在哪里初始化currentRoom以使其不为空。提前感谢您耐心等待me@Christopher,你正在初始化夏娃createRooms中的rything,因此调用该方法,编辑我的答案以在构造函数中显示代码。@Christopher,请参阅代码的“我的更新”部分,并按照它们解决问题。