• Post Reply Bookmark Topic Watch Topic
  • New Topic

Getting a single name from an arraylist...  RSS feed

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi



public String getRoomItemsGui()
{
Iterator it = currentRoom.getItems().iterator();
while(it.hasNext()) {

Item item = (Item)it.next();
return item.getName();
}
return ("None");
}





Hi, my program is basically about navigating through rooms, and in these rooms are certain items - stored in an ArrayList for the rooms items.
Basically what I want to do is iterate through the arraylist and return the item's name as a string - the item has a name and a description, but for now I don't want the description.
ATM, with this code I get nullPointer exceptions because the starting room has no items.

How do I make an if statement to handle this properly? Returning "None" if there are no items in the room, and returning the item name if there are any.

Thanks for any help.
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually this will throw a NullPointerException if currentRoom is null, or if the ArrayList itself is null, but there will be no problem if the ArrayList is simply empty. The method will return the name of the first item, or "(None)" if there are none.
 
GregK
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But what I'm trying to do (should have said this before)
Is reference this string from my GUI class (to be displayed in a text box when the rooms is entered)
I don't get anything come up ATM, and I'm kinda confused.

I'm using setText and it works for another text field which jus gets the name ofthe room, but when tryin the same thing with and ArrayList I cant get it to work.
 
Ranch Hand
Posts: 1704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about modifying your code like this:

public String getRoomItemsGui(){
if( currentRoom != null){
Iterator it = currentRoom.getItems().iterator();
while(it.hasNext()) {
Item item = (Item)it.next();
return item.getName();
}
}
return ("None");
}
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!