Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^673


The next three responsibilities are within the event handler and can be grouped to-
gether.


Have we forgotten anything? Yes—how are we going to count the number of compar-
isons? We can derive a class from one of the list classes and have it override the isThere
method. Before we do that, let’s spend a minute thinking about the processing that we
need to do. We don’t delete an item, and we don’t use any of the observers. In fact, we
aren’t really dealing with a list at all, because the number of items is a constant. It
would be much more efficient to just generate the random numbers directly into an ar-
ray, and then write an isTheremethod that searches the array and counts the number
of comparisons. We can borrow the code from one of our list classes. We use the linear
search because the array items are not in sorted order.


We have to make countbe a field in the applet class. We need two outputs from our
isTheremethod (foundand count), yet the returnstatement can only return one value.


Is there (item)
Set location to 0
Set found to false
Set count to 0
Set moreToSearch to (location less than SIZE)
whilemoreToSearch and !found
Increment count
ifitem equals values[location]
Set found to true
else
Increment location
Set moreToSearch to (location less than SIZE)
returnfound

Generate list (revised)
forcounter going from 0 to SIZE – 1
values[counter] = Math.abs(rand.nextInt()) % 1000

Event handler
Get item
Search list for item
iffound
Write item, " is in list found with ", count, " comparisons"
else
Write item, " is not in list, determined with ", count, " comparisons"
Free download pdf