// (see page 245) (from Carter book)
// This is the controlling class (containing main() method)
// and it uses the Search class method called linear()
// to find a number in the array called 'numArray'.
import java.awt.*;
import hsa.Console;
import java.lang.Math;
public class FindNum
{
static Console c; // The output console
public static void main (String[] args)
{
c = new Console ();
final int MAX = 20;
int[] numArray = new int [MAX];
// declare an int array with room for 21 elements
// (starting at 0 through 20)
int num, location;
// fill the array with 21 random numbers
for (int i = 0 ; i < numArray.length ; i++)
{
numArray [i] = (int) ((MAX + 1) * Math.random ());
} // end of for loop # 1
// prompt the user for a number to search for
c.print ("Enter a number between 0 and " + MAX + " ");
num = c.readInt ();
// now, search for that number and notify the user
// of num's location in the array, numArray.
location = Search.linear (numArray, num);
// calls the linear method in the Search class.
// the if-else statement checks to see if the
// chosen number exists - if so, it shows its location.
if (location == -1)
{
c.print ("Sorry, your number was not found ");
c.println ("in the array");
}
else
{
c.print ("First occurrence of your number is ");
c.println ("element # " + location);
} // end of if-else statement
} // end of main method
} // end of FindNum class
No comments:
Post a Comment