I am creating a game project in BlueJ but the "drop" and "items" commands do not work. When I call either one of them in the game I get a "nullpointerexception" error message.
This is the drop method in the game class, which compiles but does not work:
/**
* Drops an item
*/
private void drop(Command command)
{
String theItem = command.getSecondWord();
Item theItems = currentPlayer.getItem(theItem);
if (!command.hasSecondWord()) {
System.out.println("Drop what?");
return;
}
currentPlayer.removeItem(theItems);
System.out.println("The " + theItem + " has been removed from your inventory");
currentRoom.addItem(theItems);
}
The "nullpointerexception" error highlights the "if(anItem.getName().equals(theItem))" line of the following method in the Player class.
/**
*
*/
public Item getItem(String theItem)
{
Iterator iter = myItems.iterator();
while(iter.hasNext()) {
Item anItem = (Item) iter.next();
if(anItem.getName().equals(theItem)) {
return anItem;
}
}
return null;
}
This method for searching the inventory is in the game class:
/**
*
*/
private void inventory(Command command)
{
System.out.println(currentPlayer.getMyItemsDescription());
}
When the command is used in the game to get the inventory, a "nullpointerexception" error occurs and the following method in the Player class is displayed:
/**
*
*/
public String getMyItemsDescription()
{
String returnString = "The items in your inventory are:";
for(Iterator iter = myItems.iterator(); iter.hasNext();){
returnString += " " + ((Item)iter.next()).getDescription();
}
return returnString;
}
Any help is greatly appreciated as I am new to this and have spent hours trying to get this to work.