簡體   English   中英

將項目添加到Hashmap並得到錯誤null.pointer.exception

[英]adding items to an Hashmap and getting error null.pointer.exception

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

第一部分是我的游戲類,游戲類負責跟蹤玩家的物品和當前位置。 第二部分是我的房間類,實現一個類以維護有關房間的信息,包括:房間的描述(字符串),項目(項目)和所有相鄰房間的列表(HashMap)。

當我運行main方法測試方法時,我調用的每個方法都會得到一個null.pointer.exception。 由於某種原因(我不知道為什么),當運行調試器時,每個變量都設置為null,因此我認為這就是為什么我得到此錯誤。 關於如何解決此問題的任何幫助,或者如果我做錯了任何事情,請提供幫助。 這也是我編程的第一學期,所以我是一個初學者。

******************更新!!!! ************好吧,我更改了構造函數,似乎已經解決了這個問題? 現在我仍然在這里得到同樣的錯誤myNeighbor.put(pDirection,r); 在我的房間類中的public void addNeighbor(String pDirection,Room r)中(原始帖子的第二部分)

嘗試調試您的代碼。 而且在eclipse中,您可以添加NullPointerExeption作為斷點並進行調試。

將您的代碼包含在try and catch block ,以便您可以找到發生異常的那一行

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

並在您的問題中粘貼您的堆棧跟蹤。

編輯:

由於createRooms()是私有方法,因此必須從類方法或構造函數中調用它。

public Game()
{
    ArrayList <Item> myArray = new ArrayList();
    createRooms();
    currentRoom = hallway;
    look(); //Add this
}

然后這樣改變你的構造函數

public Room (String pDescription, Item pItem)
{
    description = pDescription;
    item = pItem;
    HashMap <String, Room> myNeighbor = new HashMap <String, Room> (); //Added
}

編輯2:

更新了Game()構造函數。

並這樣改變移動方法。

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

根據您的代碼片段,您將獲得編譯時錯誤以及無法訪問的代碼

**************************編輯*********************** *****

這樣改變你的構造函數

  public Game()
    {
        ArrayList <Item> myArray = new ArrayList();
        createRooms();
        currentRoom = hallway;
    }

默認情況下,在Java class所有實例變量都分配為null

因此,在您的Game類中,實例變量的聲明如下:

public class Game
{
    ....
    Room currentRoom;
    String currentMessage;
    ....
}

因此,顯然變量沒有任何對象,因此它們為null

現在,從您的主要方法開始,您將執行以下操作:

public static void main(String args[]){
    Game g = new Game();
    System.out.println(g.getMessage());
    g.move("west");
    ....
}

一線Game g = new Game(); Java在這里調用您的構造函數,因此代碼為:

public Game()
{
    ArrayList <Item> myArray = new ArrayList();
    currentRoom = hallway;
}

在這里,您正在將參考currentRoom分配給hallway ,這也是null因為您沒有將hallway分配給任何對象。

現在轉到下一行, Game類的getMessage()方法僅返回currentMessage實例變量null 因此, g.getMessage()的輸出為null

main方法的下一行是g.move(..) ,因此進入move()方法:

public void move(String direction)
{
   Room nextRoom = currentRoom.getNeighbor(direction);
   ...
} 

在這里,您嘗試訪問變量currentRoom而不對其進行初始化,因此它仍然是null對象,因此您將獲得java.lang.NullPointerException

更新:

因此,像這樣更改代碼:

public Game()
    {
        createRooms();
        myArray = new ArrayList();
        currentRoom = hallway;
    }

在上面的代碼中,您可以看到現在我們正在調用createRooms() ,並且myArray也已正確初始化,而不是創建新變量。

另外,您還需要像這樣初始化Room類的myNeighbor變量:

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

新更新:

像這樣更改您的move方法:

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

我刪除了msg局部變量,並在此處使用currentMessage實例變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM