CASE STUDY
672
nothing about the types of items in the list, let’s make them be integers. We can then
use a random-number generator to create the items in the list.
Responsibility AlgorithmsThe first responsibility, preparing the GUI components, is
very straightforward. We need an input label, an output label, a text field, and a button.
Generating the list requires a little more thought. The CRC card says that this operation
collaborates with the class Random. This Java class supplies a method that generates a
random number. We can call this method to give us an integer, say, between 0 and 999.
Here is how the method works:
Random rand = newRandom();
value = Math.abs(rand.nextInt()) % 1000 ;
The first line initializes the random-number generator. Each time it is called, the
nextIntmethod returns a random number within the range of the intdata type. The
Math.absmethod converts the result to a nonnegative integer, and the % 1000 limits the
values to three digits.Randomis in java.util.
Which list ADT shall we use? Does the list need to be sorted? It must be sorted only
if we decide to use the searches that require a sorted list. Abstraction lets us write the
primary algorithms without having to decide right away. What size shall we make the
list? Let’s set a constant SIZE to be 100. This way it would be easy to change later.
Generate values
forcounter going from 1 to SIZE
Generate random number
Insert number into list
Class Name: Search Superclass: Applet Subclasses:
Responsibilities Collaborations
Prepare GUI components Label, TextField, Button
Generate list values Random
Get an item
Search the list (item) List
return boolean
Report results