Java Reference
In-Depth Information
Code 6.6
continued
The getExitString
method of Room
public String getExitString()
{
String exitString = "Exits: " ;
if (northExit != null )
exitString += "north " ;
if (eastExit != null )
exitString += "east " ;
if (southExit != null )
exitString += "south " ;
if (westExit != null )
exitString += "west " ;
return exitString;
}
Because information about its exits is now stored only in the room itself, it is the room that
is responsible for providing that information. The room can do this much better than any
other object, because it has all the knowledge about the internal storage structure of the exit
data. Now, inside the Room class, we can make use of the knowledge that exits are stored in a
HashMap , and we can iterate over that map to describe the exits.
Consequently, we replace the version of getExitString shown in Code 6.6 with the version
shown in Code 6.7. This method finds all the names for exits in the HashMap (the keys in the
HashMap are the names of the exits) and concatenates them to a single String , which is then
returned. (We need to import Set from java.util for this to work.)
Exercise 6.9 Look up the keySet method in the documentation of HashMap . What does it do?
Exercise 6.10 Explain, in detail and in writing, how the getExitString method shown in
Code 6.7 works.
Code 6.7
A revised version of
getExitString
/**
* Return a description of the room's exits,
* for example "Exits: north west".
* @return A description of the available exits.
*/
public String getExitString()
{
String returnString = "Exits:" ;
Set<String> keys = exits.keySet();
for (String exit : keys) {
returnString += " " + exit;
}
return returnString;
}
 
Search WWH ::




Custom Search