Reputation: 13
I have an ArrayList in a class called Room that contains the Character object. I want to be able to print off a description that will give a list of the Characters in a Room. I have made a toString method in the character class that will return the names of the characters but cant get it to work from the Room class. Im fairly new to programming and still getting use to arrays, any help would be appreciated!
Here is the addCharacter method that adds a character to the Room arraylist.
public void addCharacter(Character c)
{
assert c != null : "Room.addCharacter has null character";
charInRoom++;
charList.add(c);
System.out.println(charList);
// TO DO
}
Here is the getLongDescription() class that I to use to print the list of characters in the room. (This is the method im having trouble with).
public String getLongDescription()
{
return "You are " + description + ".\n" + getExitString()
+ "\n" + charList[].Character.toString; // TO EXTEND
}
And here is the toString method in the Character class. This method works.
public String toString()
{
//If not null (the character has an item), character
//and item description will be printed.
if(charItem != null){
return charDescription +" having the item " + charItem.toString();
}
//Otherwise just print character description.
else {
return charDescription;
}
}
Upvotes: 0
Views: 174
Reputation: 21172
As you're using a List<Character>
, and you already implemented your custom toString
method, you can just call characters.toString()
.
public String getLongDescription() {
return "You are " + description + ".\n" + getExitString()
+ "\n" + characters; // toString implicitly called.
}
The ArrayList#toString
method will simply call each element's toString
.
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next(); // Get the element
sb.append(e == this ? "(this Collection)" : e); // Implicit call to toString
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
Upvotes: 1