Java Reference
In-Depth Information
Exercise 5.17 Write a method called getResponse that randomly returns one of the
strings "yes" , "no" , or "maybe" .
Exercise 5.18 Extend your getResponse method so that it uses an ArrayList to store
an arbitrary number of responses and randomly returns one of them.
When using a method that generates random numbers from a specified range, care must be taken
to check whether the boundaries are inclusive or exclusive. The nextInt ( int n ) method in the
Java library Random class, for example, specifies that it generates a number from 0 (inclusive) to
n (exclusive). That means that the value 0 is included in the possible results, whereas the speci-
fied value for n is not. The highest number possibly returned by this call is n-1 .
Exercise 5.19 Add a method to your RandomTester class that takes a parameter max
and generates a random number in the range 1 to max (inclusive).
Exercise 5.20 Add a method to your RandomTester class that takes two parameters,
min and max , and generates a random number in the range min to max (inclusive). Rewrite the
body of the method you wrote for the previous exercise so that it now calls this new method to
generate its result. Note that it should not be necessary to use a loop in this method.
5.4.3
Generating random responses
Now we can look at extending the Responder class to select a random response from a list of
predefined phrases. Code 5.2 shows the source code of class Responder as it is in our first version.
We shall now add code to this first version to:
declare a field of type Random to hold the random number generator;
declare a field of type ArrayList to hold our possible responses;
create the Random and ArrayList objects in the Responder constructor;
fill the responses list with some phrases;
select and return a random phrase when generateResponse is called.
Code 5.3 shows a version of the Responder source code with these additions.
Code 5.3
The Responder
source code with
random responses
import java.util.ArrayList;
import java.util.Random;
/**
* The responder class represents a response-generator object.
* It is used to generate an automatic response by randomly
* selecting a phrase from a predefined list of responses.
*
 
Search WWH ::




Custom Search