Java Reference
In-Depth Information
Code 5.4
continued
Associating selected
words with possible
responses
"Well, you know, all software has some bugs. \n" +
"But our software engineers are working very " +
"hard to fix them. \n" +
"Can you describe the problem a bit further?" );
responseMap.put( "expensive" ,
"The cost of our product is quite competitive. \n" +
"Have you looked around and " +
"really compared our features?" );
}
A first attempt at writing a method to generate the responses could now look like the gener-
ateResponse method below. Here, to simplify things for the moment, we assume that only a
single word (for example, “slow”) is entered by the user.
public String generateResponse(String word)
{
String response = responseMap.get(word);
if(response != null) {
return response;
}
else {
// If we get here, the word was not recognized. In
// this case, we pick one of our default responses.
return pickDefaultResponse();
}
}
In this code fragment, we look up the word entered by the user in our response map. If we find
an entry, we use this entry as the response. If we don't find an entry for that word, we call a
method called pickDefaultResponse . This method can now contain the code of our previ-
ous version of generateResponse , which randomly picks one of the default responses (as
shown in Code 5.3). The new logic, then, is that we pick an appropriate response if we recog-
nize a word, or a random response out of our list of default responses if we don't.
Exercise 5.33 Implement the changes discussed here in your own version of the
TechSupport system. Test it to get a feel for how well it works.
This approach of associating keywords with responses works quite well as long as the user does
not enter complete questions, but only single words. The final improvement to complete the ap-
plication is to let the user enter complete questions again and then pick matching responses if
we recognize any of the words in the questions.
This poses the problem of recognizing the keywords in the sentence that was entered by the
user. In the current version, the user input is returned by the InputReader as a single string.
We shall now change this to a new version in which the InputReader returns the input as a
 
Search WWH ::




Custom Search