Reputation: 1
Sorry I'm really new to programming. I'm messing around and making a simple text based game and I am stuck at trying to check the size of this HashMap in my conditional statement.
Here is the method:
/**
* Lists all the items in a room.
*/
public String getItemList()
{
String NoItemList = "There are no items in this room.";
String ItemList = "Items:"; Set<String> keys = items.keySet();
for(String item : keys)
{
ItemList += " " + item;
}
if (items.size < 1)
{
return NoItemList;
}
if (items.size > 1)
{
return ItemList;
}
}
How can I get it to work so that if there are items in the HashMap it will return ItemList, and if there are none to return NoItemList?
Thanks
Upvotes: 0
Views: 3099
Reputation: 94469
On HashMap
or Collection
(which HashMap
implements) size is a method use:
items.size()
The conditional could be rewrote to:
if (items.size() < 1)
{
return NoItemList;
}else{
return ItemList;
}
Or if your comfortable with ternary expressions:
return (items.isEmpty()) ? NoItemList:ItemList;
Notice this form of the method uses the isEmpty() method which is a shortcut for checking if the list does not contain any items.
Upvotes: 2
Reputation: 4923
You can use size()
method to check the size of hashMap as below :
ItemList.size() --> Return the size of map
Upvotes: 0
Reputation: 1421
Fixed code:
if (items.size() == 0)
{
return NoItemList;
}
if (items.size() > 0)
{
return ItemList;
}
Upvotes: 0