Java Reference
In-Depth Information
The input variable receiving the result from reader.getInput() is now of type HashSet .
The check for ending the application is done using the contains method of the HashSet
class, rather than a String method. (Look this method up in the documentation.)
The HashSet class has to be imported using an import statement (not shown here).
Finally, we have to extend the generateResponse method in the Responder class to accept
a set of words as a parameter. It then has to iterate over these words and check each of them
with our map of known words. If any of the words is recognized, we immediately return the
associated response. If we do not recognize any of the words, as before, we pick one of our
default responses. Code 5.7 shows the solution.
Code 5.6
Final version of the
start method
public void start()
{
boolean finished = false ;
printWelcome();
while (!finished) {
HashSet<String> input = reader.getInput();
if (input.contains( "bye" )) {
finished = true ;
}
else {
String response = responder.generateResponse(input);
System.out.println(response);
}
}
printGoodbye();
}
Code 5.7
Final version of the
generate Response
method
public String generateResponse(HashSet<String> words)
{
for (String word : words) {
String response = responseMap.get(word);
if (response != null ) {
return response;
}
}
// If we get here, none of the words from the input line was
// recognized. In this case, we pick one of our default
// responses.
return pickDefaultResponse();
}
 
Search WWH ::




Custom Search