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

The first section is my game class, The Game class is responsible for keeping track of the player’s items and the current location. The second section is my room class, Implement a class to maintain information about a room including: a description of the room (String), an item (Item) and a list of all adjacent Rooms (HashMap).

When I run the main method to test the methods, I get a null.pointer.exception with every method I call. For some reason (I do not know why) Every variable is set to null when I run the debugger, so I assume this is why I am getting the error. Any help with how I can fix this or if there is anything I am doing wrong please do help. Also this is my first semester of programming so I am a semi beginner.

******************UPDATE!!!!************ Ok I changed my constructor and it seemed to have fixed that? now I still get the same error here myNeighbor.put(pDirection, r); which is in public void addNeighbor(String pDirection, Room r) in my room class (the second section from original post)

3 Answers3

0

Try to debug your code. And also in eclipse you can add NullPointerExeption as your breakpoint and debug.

Enclose your code in try and catch block, so that you can find at which line you are getting exception

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

And paste your stack trace in your question.

Edit:

As createRooms() is private method, it must be called from class method or constructor.

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

And change your constructor this way

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

Edit2:

Updated Game() constructor.

And change move method like this.

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();
    }
}
Naman Gala
  • 4,670
  • 1
  • 21
  • 55
0

are you sure this is the code u ran?? First of all look at your main method

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

according to your code snippet you will get compile time errors plus unreachable code also

**************************Edited****************************

change your constructor like this

  public Game()
    {
        ArrayList <Item> myArray = new ArrayList();
        createRooms();
        currentRoom = hallway;
    }
Sumit Jain
  • 87
  • 9
  • Yes this is the main method I ran, it complies but when I run it I get the error immediately when I first try to move. – Christopher Nov 26 '14 at 05:29
  • where is initialisation part of variable g.?? and shouldn't you close the main method like `public static void main(String ar){ **code** }` – Sumit Jain Nov 26 '14 at 05:30
  • Oh wow I dont know why it didnt copy and paste right but yes here is the code I used: public static void main(String args[]) { Game g = new Game(); System.out.println(g.getMessage()); then the rest is the same – Christopher Nov 26 '14 at 05:35
  • I think if you have initialised everything properly but where is the initialisation part of `hallway` ?? I think the `currentRoom` is `null` – Sumit Jain Nov 26 '14 at 05:37
  • call `createRooms` method first and them try. or call `createRooms` in your constructor as the first statement – Sumit Jain Nov 26 '14 at 05:39
  • where should I initialize hallway? I set currentRoom = hallway. What else do I need to do so currentRoom is not null? – Christopher Nov 26 '14 at 05:41
  • Ok I changed my constructor and it seemed to have fixed that? now I still get the same error here myNeighbor.put(pDirection, r); which is in public void addNeighbor(String pDirection, Room r) in my room class (the second section from original post) – Christopher Nov 26 '14 at 05:53
  • provide the updated code of yours then i'll try that on my end. – Sumit Jain Nov 26 '14 at 06:46
0

By default all the instance variables of a class are assigned to null in Java.

So in your Game class the instance variables are declared like this:

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

So obviously the variables are not having any objects so they are null.

Now from your main method you are doing like this:

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

Coming to first line Game g = new Game(); here Java calls the your constructor so the code is:

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

Here you are assigning the reference currentRoom to hallway which is also null because you are not assigned hallway to any object.

Now coming to next line, the getMessage() method of Game class is just returning currentMessage instance variable which is null. So the output of g.getMessage() is null.

The next line of main method which is g.move(..), so coming to your move() method:

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

Here you are trying to access the variable currentRoom without initialising it so it still null object so you are getting java.lang.NullPointerException

Update:

So change the code like this:

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

in above code you can see that now we are calling createRooms() and also myArray is initialized properly instead of creating a new variable.

Also you need to initialize the myNeighbor variable of Room class like this:

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

New Update:

Change your move method like this:

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

I have removed the msg local variable and using the currentMessage instance variable here.

Chaitanya
  • 15,403
  • 35
  • 96
  • 137
  • Yes but in public Game() I go on on to initalize those instance variables – Christopher Nov 26 '14 at 05:44
  • @Christopher, added clear explanation to show why the variables are null, please check. – Chaitanya Nov 26 '14 at 05:49
  • Ok I am following you and it is making sense to me now, where do I need to initialize currentRoom so that it is not null. Thank you in advance for being patient with me – Christopher Nov 26 '14 at 05:49
  • @Christopher, You are initializing everything inside createRooms() so call that method, edited my answer to show the code in constructor. – Chaitanya Nov 26 '14 at 05:51
  • @Christopher, see my update section of code, and follow them to fix your issue. – Chaitanya Nov 26 '14 at 05:59
  • Alright so as of your latest edit, the take method now works, but the move method still returns null. Also when I call g.getMessage() it returns null, currentMessage is still set to null too. – Christopher Nov 26 '14 at 06:07
  • @Christopher, please try to understand your code so you will be able to fix any kind of issues. In move method you are creating a local variable `msg` to store the message which is not correct. I have updated the move method, see my `new update` section to fix the issue. – Chaitanya Nov 26 '14 at 06:12
  • ok so now the move method and take seem to work well, but when I run it I still get a null the very first print line, do you know what this could be? – Christopher Nov 26 '14 at 06:18
  • @Christopher, please read my answer, it is mentioned why it is `null`. -- `Now coming to next line, the getMessage() method of Game class is just returning currentMessage instance variable which is null. So the output of g.getMessage() is null.` So to avoid this `null` give some default value to `currentMessage` in constructor or just remove the first line of g.getMessage() in main method. – Chaitanya Nov 26 '14 at 06:20
  • Ok I think I have a good base to work off of thank you so much, I will post more here tomorrow with a update, will you be checking? You are a great help and it is very appreciated. – Christopher Nov 26 '14 at 06:24
  • I will check if I get an alert message in SO. If it solves the issue you have posted then please accept this as an answer. – Chaitanya Nov 26 '14 at 06:25
  • Before I leave do you have any advice to fix my drop method ? – Christopher Nov 26 '14 at 06:26
  • @Christopher, the method seems to be not correct for me, but I cannot comment on it unless I understand your requirement fully. But the `myArray` do not have any elements in it, so the method will just return back without doing anything. Also you are trying to remove element at a given index 2 times from the arrya. – Chaitanya Nov 26 '14 at 06:32
  • With this drop method I am trying to add the item from myArray (which acts as an inventory) to the room. So basically I want to delete it from myArray and add it to the room. – Christopher Nov 26 '14 at 06:35
  • @Christopher, then modify your constructor and add the rooms to `myArray` so it contains all the rooms. Then in `drop` method, call the remove method of `myArray` only in `if` condition. As per your code you are removing all the elements of array outside if condition which is not correct. Please try and if you have issues then ask another question in SO. Happy coding. – Chaitanya Nov 26 '14 at 06:40