Java Reference
In-Depth Information
Exercise 5.10 Find the equals method in the documentation for class String . What is
the return type of this method?
Exercise 5.11 Change your implementation to use the equals method instead of
startsWith .
Adding random behavior
So far, we have made a small improvement to the TechSupport project, but overall it remains
very basic. One of the main problems is that it always gives the same response, independent of
the user's input. We shall now improve this by defining a set of plausible phrases with which to
respond. We will then have the program randomly choose one of them each time it is expected
to reply. This will be an extension of the Responder class in our project.
To do this, we will use an ArrayList to store some response strings, generate a random in-
teger number, and use the random number as an index into the response list to pick one of our
phrases. In this version, the response will still not depend on the user's input (we'll do that
later), but at least it will vary the response and look a lot better.
First, we have to find out how to generate a random integer number.
Random and pseudo-random Generating random numbers on a computer is actually not as
easy to do as one might initially think. Because computers operate in a very well-defined, determin-
istic way that relies on the fact that all computation is predictable and repeatable, they provide little
space for real random behavior.
Researchers have, over time, proposed many algorithms to produce seemingly random sequences
of numbers. These numbers are typically not really random, but follow complicated rules. They are
therefore referred to as pseudo-random numbers.
In a language such as Java, the pseudo-random number generation has fortunately been imple-
mented in a library class, so all we have to do to receive a pseudo-random number is to make
some calls to the library.
If you want to read more about this, do a web search for “pseudo random numbers.”
5.4.1 The Random class
The Java class library contains a class named Random that will be helpful for our project.
Exercise 5.12 Find the class Random in the Java class library documentation. Which pack-
age is it in? What does it do? How do you construct an instance? How do you generate a
random number? Note that you will probably not understand everything that is stated in the
documentation. Just try to find out what you need to know.
Exercise 5.13 Write a small code fragment (on paper) that generates a random integer
number using this class.
Search WWH ::

Custom Search