Computer Science 122
Assignment 4
Due: October 7. 2003

You are next to change the frame that you created for assignment 3 so that a user can find a product in the list.  The frame should now have a TextField that can be used to get the product ID from the user.  When the button is clicked this time, it should display just the one product and not the entire list.

Add a method to the product class that will find a product in the list given its ID.  If it is found, return it.  Otherwise return null.  A sample method follows:

 // find Product returns the object with the id, keyId if it is in the list.  If not, it returns null.
 public Product find Product (String keyId)
 {
      boolean found = false;
      int count = 0;
      while (!found && (count < listSize))
      {
           if (list[count].getId ().equals (keyId)) found = true;
           else count ++;
      }
      if (count == listSize) return null;
      else return list [count];
 } // find Product

The actionPerformed method in the listener inner class should now get the ID from the TextField and call the find method in the class that manages the list.  If the result returned is null, it should display a message in either the TextArea or the TextField.  If it is not null, display the product data in the TextArea.

You will have to be able to check the ID’s of all the products in the array.  In order to do this, add a ‘get’ method to the Product class.
     public String getId () {return id;}
This is needed since the id field is private in the Product class and so cannot be accessed by the class that handles the list.

As before, separate the code for the model from that for the view.  Hand in a printout of your program and a disk with the files.  If you send it to me by e-mail, zip the files up before attaching the file.

Note: Another way to write the code for searching is as follows:

 // findProduct returns the object with the id, keyId if it is in the list.  If not, it returns null.
 public Product findProduct (String keyId)
 {
      int count = 0;
      while ((count < listSize) && (!list[count].getId().equals (keyId)))
           count ++;
      if (count == listSize) return null;
      else return list [count];
 } // findProduct

It is generally not a good idea to use a ‘for’ loop when searching.  For loops look through the entire array.  With a while loop the program exits the loop as soon as the object is found.