CASE STUDY
674
Therefore, we must make countbe a field that other methods can access. Here is the
code for our applet, followed by a picture showing execution by the applet viewer:
//***********************************************************
// This applet prompts a user to input an integer value and
// reports if the value is in a list and how many comparisons
// it took to make that determination.
//***********************************************************
importjava.applet.Applet;
importjava.awt.*; // Supplies user interface classes
importjava.awt.event.*; // Supplies event classes
importjava.util.*; // Supplies Random class
public classSearch extendsApplet implementsActionListener
{
private int[] values; // Values to be searched
private intcount = 0 ; // Comparison count
private final intSIZE = 100 ; // Size of the array
// Event handler method
public voidactionPerformed(ActionEvent event)
{
intvalue;
value = Integer.parseInt(inputField.getText());
inputField.setText("");
if(isThere(value))
outLabel.setText(value + " is in list found with "
+ count + " comparisons");
else
outLabel.setText(value + " is not in list determined with "
+ count + " comparisons");
}
private booleanisThere (intitem)
// Returns true if the item is in the array;
// otherwise, returns false
{
booleanmoreToSearch;
intlocation = 0 ;
booleanfound = false;
count = 0 ;
moreToSearch = (location < SIZE);