Java Reference
In-Depth Information
program). We make sure that it is initially
false
. (Remember that the exclamation mark is a
not
operator!)
The main part of the loop—the part that is done repeatedly while we wish to continue—consists
of three statements if we strip it of the check for the exit condition:
String input = reader.getInput();
...
String response = responder.generateResponse();
System.out.println(response);
Thus, the loop repeatedly
■
reads some user input,
■
asks the responder to generate a response, and
■
prints out that response.
(You may have noticed that the response does not depend on the input at all! This is certainly
something we shall have to improve later.)
The last part to examine is the check of the exit condition. The intention is that the program
should end once a user types the word 'bye'. The relevant section of source code we find in the
class reads
String input = reader.getInput();
if(input.startsWith("bye")) {
finished = true;
}
If you understand these pieces in isolation, then it is a good idea to look again at the complete
start
method in Code 5.1 and see whether you can understand everything together.
In the last code fragment examined above, a method called
startsWith
is used. Because that
method is called on the
input
variable, which holds a
String
object, it must be a method of
the
String
class. But what does this method do? And how do we find out?
We might guess, simply from seeing the name of the method, that it tests whether the input
string starts with the word “bye”. We can verify this by experiment. Run the
TechSupport
system again and type “bye bye” or “bye everyone”. You will notice that both versions cause
the system to exit. Note, however, that typing “Bye” or “ bye”—starting with a capital letter
or with a space in front of the word—is not recognized as starting with “bye”. This could be
slightly annoying for a user, but it turns out that we can solve these problems if we know a bit
more about the
String
class.
How do we find out more information about the
startsWith
method or other methods of the
String
class?
5.3
Reading class documentation
The class
String
is one of the classes of the standard Java class library. We can find out more
details about it by reading the library documentation for the
String
class.
Search WWH ::
Custom Search