I'm working on a text-based adventure game project. It involves rooms with items in them and navigating from room to room. There's a class called Item and this larger class called Room. All of my methods work perfectly except my addItem method. It's supposed to put an item into an empty room or replace the room's item if it's already there. I can put an item into a room when I create a new room, and my removeItem method works, but addItem works with neither empty nor full rooms. Am I missing some kind of "room" variable (my professor didn't mention anything like that) or is my problem with the item variable? Here is the full code for class Room:
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){
i = item;
}
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;
}
}
change i = item;
for item = i;
public void addItem (Item i){
item = i;
}
Was it this error?
Hope this helps.
Phil
What is happening is that you are giving i
, the parameter, a reference to item
, the instance variable, instead of the other way around. The method ends and i
no longer exists, nothing has changed.