All pastes #498378 Raw Edit

Unnamed

public text v1 · immutable
·published 2007-05-20 11:06 UTC
rendered paste body
import java.util.ArrayList;
import java.util.Scanner;

// CLASS: ESotre
// DESCRIPTION:
//    This class represents a main driver class that runs the E-shopping store
//    system.
// AUTHOR:  Rafe Taya
// VERSION: 1 (April 5, 2007).

public class EStore
{
   private Catalogue catalogue;
   private UserDatabase users;
   private User currentUser;
   private Scanner in;

   private static final int EXIT                = 3;
   private static final int ADMIN_BACK_TO_MAIN  = 11;
   private static final int CUST_BACK_TO_MAIN   = 7;

   private static final String CATALOGUE_FILE = "catalogue.ser";
   private static final String USERS_FILE = "users.ser";

   // default constructor
   public EStore()
   {
      // set up the inital list of catalogue
      catalogue = new Catalogue();
      catalogue.load(CATALOGUE_FILE);     // load data from catalog file

      // set up the inital list of customers
      users = new UserDatabase();
      users.load(USERS_FILE);             // load data from users file

      currentUser = null;
      in = new Scanner(System.in);
   }

   // Method:  begin
   // Purpose: commence  the system for e-shopping store
   // Input:   obtains the main menu choice from the user
   // Output:  the main menu
   public void begin()
   {
      System.out.println("Welcome to E-Shopping Store System");
      System.out.println();

      System.out.println("Login");
      System.out.println("=====");

      // get username
      System.out.print("Username: ");
      String username = in.nextLine();

      // get password
      System.out.print("Password: ");
      String password = in.nextLine();

      currentUser = users.validLogin(username, password);

      // validate login
      while (currentUser == null)
      {
         System.out.println("Error: Invalid login! Please try again.");

         // get username
         System.out.print("Username: ");
         username = in.nextLine();

         // get password
         System.out.print("Password: ");
         password = in.nextLine();

         currentUser = users.validLogin(username, password);
      }

      // display menu based on the type of user
      processMainMenu(currentUser.getType());

      // save data to files
      catalogue.save(CATALOGUE_FILE);
      users.save(USERS_FILE);

      System.out.println("Thank you for using this program!");
   }

   // Method:  processMainMenu
   // Purpose: to perform the action requested by the user
   // Passed:  choice - the choice of the main menu
   // Input:   obtains the submenu choices from the user
   // Output:  the submenu
   private void processMainMenu(int type)
   {
      int choice = 0;

      switch(type)
      {
         case User.ADMINISTRATOR:

            do
            {
               System.out.println();
               System.out.println("Administrator Menu");
               System.out.println("==================");
               System.out.println();
               System.out.println(" 1. Add a new CD to the catalogue");
               System.out.println(" 2. Add a new DVD to the catalogue");
               System.out.println(" 3. Display all CDs in the catalogue");
               System.out.println(" 4. Display all DVDs in the catalogue");
               System.out.println(" 5. Display all items in the catalogue");
               System.out.println(" 6. Display all customers - showing the customers names");
               System.out.println(" 7. Remove an item from the catalogue");
               System.out.println(" 8. Register a new customer");
               System.out.println(" 9. Report summary information of a particular customer");
               System.out.println("10. Display the shopping cart linked to a particular customer account");
               System.out.println("11. Back to Main Menu");
               System.out.println();

               // Get submenu choice from the user
               try
               {
                  System.out.print("Enter your choice: ");
                  choice = Integer.parseInt(in.nextLine());
               }
               catch (Exception e) { }

               processAdminMenuChoice(choice);

               // pause the screen
               if (choice != ADMIN_BACK_TO_MAIN)
               {
                  System.out.print("Press <Enter> to continue ... ");
                  String line = in.nextLine();
               }
            }
            while (choice != ADMIN_BACK_TO_MAIN);
            break;

         case User.CUSTOMER:
            Customer cust = getCustomer();

            do
            {
               System.out.println();
               System.out.println("Customer Menu");
               System.out.println("==================");
               System.out.println();
               System.out.println("1. Display all CDs in the catalogue");
               System.out.println("2. Display all DVDs in the catalogue");
               System.out.println("3. Display all items in the catalogue");
               System.out.println("4. Display all items in the shopping cart");
               System.out.println("5. Add product to the shopping cart");
               System.out.println("6. Remove product from the shopping cart");
               System.out.println("7. Back to Main Menu");
               System.out.println();

               // Get submenu choice from the user
               try
               {
                  System.out.print("Enter your choice: ");
                  choice = Integer.parseInt(in.nextLine());
               }
               catch (Exception e) { }

               processCustMenuChoice(choice, cust);

               // pause the screen
               if (choice != CUST_BACK_TO_MAIN)
               {
                  System.out.print("Press <Enter> to continue ... ");
                  String line = in.nextLine();
               }
            }
            while (choice != CUST_BACK_TO_MAIN);
            break;

         case EXIT:
            break;

         default:
            System.out.println("Error: Invalid choice!");
      }
   }

   // Method:  processAdminMenuChoice
   // Purpose: to perform the action requested by the user
   // Passed:  choice - the choice of the administrator submenu
   // Output:  the outcome of the required action and the error message for invalid choice
   private void processAdminMenuChoice(int choice)
   {
      switch(choice)
      {
         case 1:
            ((Administrator) currentUser).addProduct(Administrator.CD, catalogue);
            break;
         case 2:
            ((Administrator) currentUser).addProduct(Administrator.DVD, catalogue);
            break;
         case 3:
            System.out.println(catalogue.toCatalogueString(CD.TYPE));
            break;
         case 4:
            System.out.println(catalogue.toCatalogueString(DVD.TYPE));
            break;
         case 5:
            System.out.println(catalogue.toCatalogueString());
            break;
         case 6:
            System.out.println(users.toCustomersString());
            break;
         case 7:
            ((Administrator) currentUser).removeProduct(catalogue);
            break;
         case 8:
            ((Administrator) currentUser).createCustomer(users);
            break;
         case 9:
            reportCustomerSummary();
            break;
         case 10:
            displayCustomerShoppingCart();
            break;
         case ADMIN_BACK_TO_MAIN:     // Back to main menu
            break;
         default:
            System.out.println("Error: Invalid choice!");
      }
   }

   // Method:  processCustMenuChoice
   // Purpose: to perform the action requested by the user
   // Passed:  choice - the choice of the customer submenu
   //          cust - the customer object
   // Output:  the outcome of the required action and the error message for invalid choice
   private void processCustMenuChoice(int choice, Customer cust)
   {
      switch(choice)
      {
         case 1:
            System.out.println(catalogue.toCatalogueString(CD.TYPE));
            break;
         case 2:
            System.out.println(catalogue.toCatalogueString(DVD.TYPE));
            break;
         case 3:
            System.out.println(catalogue.toCatalogueString());
            break;
         case 4:
            cust.showShoppingCart();
            break;
         case 5:
            addProductToShoppingCart(cust);
            break;
         case 6:
            removeProductFromShoppingCart(cust);
            break;
         case CUST_BACK_TO_MAIN:     // Back to main menu
            break;
         default:
            System.out.println("Error: Invalid choice!");
      }
   }

   // Method:  addProductToShoppingCart
   // Purpose: To add a product in the shopping cart.
   // Passed:  cust - the customer object
   // Input:   obtains product choice from the scanner connected to the standard-input device.
   // Output:  the outcome message for addition and the prompt message for input
   private void addProductToShoppingCart(Customer cust)
   {
      if (catalogue.size() > 0)
      {
         int prodChoice = 0;

         System.out.println("\nPlease select a product");
         System.out.println(catalogue.toCatalogueMenuString());

         try
         {
            System.out.print("Enter your choice: ");
            prodChoice = Integer.parseInt(in.nextLine());
         }
         catch (Exception e) { }

         while (prodChoice < 1 || prodChoice > catalogue.size())
         {
            System.out.println("Error: invalid choice!");
            System.out.println("\nPlease select a product:");
            System.out.println(catalogue.toCatalogueMenuString());

            try
            {
               System.out.print("Enter your choice: ");
               prodChoice = Integer.parseInt(in.nextLine());
            }
            catch (Exception e) { }
         }

         Product prod = (Product) catalogue.get(prodChoice - 1);

         if (cust.addProduct(prod))
            System.out.println("The product has been added...");
         else
            System.out.println("Sorry! There are too many items in your shopping cart.");
      }
      else
      {
         System.out.println("There is nothing in the catalogue.");
      }
   }

   // Method:  removeProductFromShoppingCart
   // Purpose: To remove a product in the shopping cart.
   // Passed:  cust - the customer object
   // Input:   obtains product choice from the scanner connected to the standard-input device.
   // Output:  the outcome message for addition and the prompt message for input
   private void removeProductFromShoppingCart(Customer cust)
   {
      if (cust.getNumItems() > 0)
      {
         int prodChoice = 0;

         System.out.println("\nPlease select a product");
         cust.showShoppingCart();

         try
         {
            System.out.print("\nEnter your choice (1-" + cust.getNumItems() + "): ");
            prodChoice = Integer.parseInt(in.nextLine());
         }
         catch (Exception e) { }

         while (prodChoice < 1 || prodChoice > cust.getNumItems())
         {
            System.out.println("Error: invalid choice!");
            System.out.println("\nPlease select a product:");
            cust.showShoppingCart();

            try
            {
               System.out.print("\nEnter your choice (1-" + cust.getNumItems() + "): ");
               prodChoice = Integer.parseInt(in.nextLine());
            }
            catch (Exception e) { }
         }

         Product prod = cust.getProduct(prodChoice - 1);

         if (prod != null)
         {
            if (cust.removeProduct(prod.getProductNumber()))
               System.out.println("The product has been removed...");
            else
               System.out.println("Sorry! The product failed to be removed...");
         }
         else
            System.out.println("Sorry! The product failed to be removed...");
      }
      else
      {
         System.out.println("There is nothing in the shopping cart.");
      }
   }

   // Method:  reportCustomerSummary
   // Purpose: reports the summary of the customer
   private void reportCustomerSummary()
   {
      Customer cust = getCustomer();
      cust.showSummary();
   }

   // Method:  displayCustomerShoppingCart
   // Purpose: displays the shopping car of the customer
   private void displayCustomerShoppingCart()
   {
      Customer cust = getCustomer();
      cust.showShoppingCart();
   }

   // Method:  getCustomer
   // Purpose: retrieves the chosen customer by the user from the system
   // Returns: the customer object
   // Input:   obtains customer choice from the scanner connected to the standard-input device.
   // Output:  the outcome message if no customers in the system and the prompt message for input
   private Customer getCustomer()
   {
      Customer cust = null;
      System.out.println();

      if (users.sizeOfCustomers() == 0)
      {
         System.out.println("There is no customers recorded in the system.");
      }
      else
      {
         int choice = 0;

         System.out.println("Please select a customer:");
         System.out.println(users.toCustomersString());

         try
         {
            System.out.print("Enter your choice (1-" + users.sizeOfCustomers() + "): ");
            choice = Integer.parseInt(in.nextLine());
         }
         catch (Exception e) { }

         while (choice < 1 || choice > users.sizeOfCustomers())
         {
            System.out.println("Error: invalid choice!");
            System.out.println("\nPlease select a customer:");
            System.out.println(users.toCustomersString());

            try
            {
               System.out.print("Enter your choice (1-" + users.sizeOfCustomers() + "): ");
               choice = Integer.parseInt(in.nextLine());
            }
            catch (Exception e) { }
         }

         // search for the (choice)-th customer in users list
         for (int i = 0, j = 0; i < users.size(); i++)
         {
            if (users.get(i).getType() == User.CUSTOMER)
            {
               if (j == choice - 1)
               {
                  cust = (Customer) users.get(i);
               }
               j++;
            }
         }
      }

      return cust;
   }

   /////////////////////////////
   //   Program Entry Point   //
   /////////////////////////////

   public static void main(String[] args)
   {
      EStore eStore = new EStore();
      eStore.begin();
   }
}



import java.io.Serializable;

// CLASS: User
// DESCRIPTION:
//    This class represents a user in E-shopping store that sells CDs and
//    DVDs.
// AUTHOR:  Rafe Taya
// VERSION: 1 (April 20, 2007).

public abstract class User implements Serializable
{
	private String name;
   private String address;
   private String phone;
	private String email;
	private int type;          // type of user
	private String username;
	private String password;

   public static final int ADMINISTRATOR = 1;
   public static final int CUSTOMER = 2;
   public static final String[] typeStrings = {"", "Administrator", "Customer"};

   public static final int USERNAME_LENGTH = 6;
   public static final int PASSWORD_LENGTH = 8;

	// Non-default Constructor
   public User(String name, String address, String phone, String email,
               String username, String password)
   {
      this.name = name;
      this.address = address;
      this.phone = phone;
      this.email = email;
      this.username = username;
      this.password = password;
   }

   // Method:  getName
   // Purpose: To return the name of the user.
   // Returns: the string containing the name
   public String getName()
   {
      return name;
   }

   // Method:  getAddress
   // Purpose: To return the address of the user.
   // Returns: the string containing the address
   public String getAddress()
   {
      return address;
   }

   // Method:  getArtiste
   // Purpose: To return the artiste of the user.
   // Returns: the string containing the artiste
   public String getPhone()
   {
      return phone;
   }

   // Method:  getEmail
   // Purpose: To return the email of the user.
   // Returns: the string containing the email
   public String getEmail()
   {
      return email;
   }

   // Method:  getUsername
   // Purpose: To return the username of the user.
   // Returns: the string containing the username
   public String getUsername()
   {
      return username;
   }

   // Method:  getPassword
   // Purpose: To return the password of the user.
   // Returns: the string containing the password
   public String getPassword()
   {
      return password;
   }

   /**
    * Set the type of this product.
    * @param type type of the product.
    */
   public void setType(int type)
   {
      this.type = type;
   }

   /**
    * Return the type of this product.
    * @return type of this product.
    */
   public int getType()
   {
      return type;
   }

   /**
    * Return the type String for this product.
    * @return Sting for this product's type.
    */
   public String getTypeString()
   {
      return typeStrings[type];
   }

   // Method:  validLogin
   // Purpose: To check if the login is valid.
   public boolean validLogin(String username, String password)
   {
      return this.username.equals(username) &&
             this.password.equals(password);
   }

   // Method:  toString
   // Purpose: To return the state of this user as a string.
   // Output:  the summary information of the user
   public String toString()
   {
      return "Name:    " + name + " (" + getTypeString() + ")" + "\n" +
             "Address: " + address + "\n" +
             "Phone:   " + phone + "\n" +
             "Email:   " + email;
   }
}



import java.io.*;
import java.util.ArrayList;

// CLASS: UserDatabase
// DESCRIPTION:
//    This class represents a users in E-shopping store that sells CDs and
//    DVDs.
// AUTHOR:  Rafe Taya
// VERSION: 1 (May 10, 2007).

public class UserDatabase
{
   private ArrayList<User> users;

   // Default Constructor
   public UserDatabase()
   {
      users = new ArrayList<User>();


      // add two users to the array list
      User user1 = new Customer("Rafe Taya", "1213 North Road", "123456789",
                                "rafe@email.com", "rafe00", "00000000");
      User user2 = new Customer("Jack Bowel", "1 Station Street", "234567890",
                                "jack@abc.com", "jack00", "00000000");
      User user3 = new Administrator("Tim", "1213 North Road", "123456789",
                                     "tim@email.com", "tim000", "00000000");
      User user4 = new Administrator("Chris", "1 Station Street", "234567890",
                                     "chris@abc.com", "chris0", "00000000");

      users.add(user1);
      users.add(user3);
      users.add(user2);
      users.add(user4);

   }

   /**
    * Add the given user to the catalog.
    * @param user user to be added.
    * @return true when the user is added, otherwise, false.
    */
   public void add(User user)
   {
      users.add(user);
   }

   /**
    * Remove a user with the given user ID.
    * @param index the position of the user in array list.
    * @return true when the user is removed, otherwise, false.
    */
   public User remove(int index)
   {
      return (User) users.remove(index);
   }

   /**
    * Get a user from the catalog.
    * @param index the user index.
    * @return user at the given index.
    */
   public User get(int index)
   {
      return (User) users.get(index);
   }

   /**
    * Return number of users in the catalog.
    * @return number of users.
    */
   public int size()
   {
      return users.size();
   }

   /**
    * Return number of administrators in the catalog.
    * @return number of administrators.
    */
   public int sizeOfAdministrators()
   {
      int count = 0;

      for (int i = 0; i < users.size(); i++)
      {
         if (get(i).getType() == User.ADMINISTRATOR)
            count++;
      }

      return count;
   }

   /**
    * Return number of customers in the catalog.
    * @return number of customers.
    */
   public int sizeOfCustomers()
   {
      int count = 0;

      for (int i = 0; i < users.size(); i++)
      {
         if (get(i).getType() == User.CUSTOMER)
            count++;
      }

      return count;
   }

   // Method:  toAdministratorsString
   // Purpose: to return all administrator in the array list as a string.
   // Returns: the string containing all administrator in the array list
   public String toAdministratorsString()
   {
      String output = "\n";

      if (sizeOfAdministrators() == 0)
      {
         output = output + "There is no administrators recorded in the system.";
      }
      else
      {
         for (int i = 0, j = 0; i < users.size(); i++)
         {
            if (get(i).getType() == User.ADMINISTRATOR)
            {
               output = output + (j + 1) + ". " + get(i).getName() + "\n";
               j++;
            }
         }
      }

      return output;
   }

   // Method:  toCustomersString
   // Purpose: to return all customer in the array list as a string.
   // Returns: the string containing all customer in the array list
   public String toCustomersString()
   {
      String output = "\n";

      if (sizeOfCustomers() == 0)
      {
         output = output + "There is no customers recorded in the system.";
      }
      else
      {
         for (int i = 0, j = 0; i < users.size(); i++)
         {
            if (get(i).getType() == User.CUSTOMER)
            {
               output = output + (j + 1) + ". " + get(i).getName() + "\n";
               j++;
            }
         }
      }

      return output;
   }

   // Method:  validLogin
   // Purpose: To check if the login is valid.
   // Return:  The User object if the login is found
   //          null otherwise
   public User validLogin(String username, String password)
   {
      for (int i = 0; i < users.size(); i++)
         if (get(i).validLogin(username, password))
            return get(i);

      return null;
   }

   /**
    * Find whether or not a username exists in the database.
    * @param username the username
    */
   public boolean contains(String username)
   {
      for (int i = 0; i < users.size(); i++)
         if (get(i).getUsername().equals(username))
            return true;

      return false;
   }

   /**
    * Read a list of users as an ArrayList object from a file.
    * @param file the binary file that contains the ArrayList object
    */
   public void load(String file)
   {
      try
      {
         FileInputStream fileIn = new FileInputStream(file);
         ObjectInputStream in   = new ObjectInputStream(fileIn);
         users = (ArrayList) in.readObject();
      }
      catch (FileNotFoundException fnfe)
      {
         System.out.println(fnfe);
      }
      catch (StreamCorruptedException sce)
      {
         System.out.println(sce);
      }
      catch (IOException ioe)
      {
         System.out.println(ioe);
      }
      catch (ClassNotFoundException cnfe)
      {
         System.out.println(cnfe);
      }
   }

   /**
    * Write a list of users as an ArrayList object to a file.
    * @param file the binary file that contains the ArrayList object
    */
   public void save(String file)
   {
      try
      {
         FileOutputStream fileOut = new FileOutputStream(file);
         ObjectOutputStream out   = new ObjectOutputStream(fileOut);
         out.writeObject(users);
      }
      catch(FileNotFoundException fnfe)
      {
         System.out.println(fnfe);
      }
      catch (IOException ioe)
      {
         System.out.println(ioe);
      }
   }
}



import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;

// CLASS: Administrator
// DESCRIPTION:
//    This class represents a customer in E-shopping store that sells CDs and
//    DVDs.
// AUTHOR:  Rafe Taya
// VERSION: 1 (April 1, 2007).

public class Administrator extends User
{
   private Scanner in;

   public static final int CD = 0;
   public static final int DVD = 1;

   // Non-Default Constructor
   public Administrator(String name, String address, String phone, String email,
                        String username, String password)
   {
      super(name, address, phone, email, username, password);
      setType(ADMINISTRATOR);
      in = new Scanner(System.in);
   }

   // Method:  addProduct
   // Purpose: To add a product in the catalogue.
   // Passed:  type - the type of the product to be added
   //          catalogue - array  list of the products catalogue
   // Input:   obtains product details from the scanner connected to the standard-input device.
   // Output:  the prompt message for input
   public void addProduct(int type, Catalogue catalogue)
   {
      Product newItem = null;

      System.out.println();
      System.out.println("-- New Product Details --");

      // Request and obtain the product's title
      System.out.print("Enter title: ");
      String title = in.nextLine();

      while (title.trim().length() == 0)
      {
         System.out.println("Error: Invalid title!");
         System.out.print("Enter title: ");
         title = in.nextLine();
      }

      // Request and obtain the product's price
      double price = -1;

      try
      {
         System.out.print("Enter price: ");
         price = Double.parseDouble(in.nextLine());
      }
      catch (Exception e) { }

      while (price < 0)
      {
         System.out.println("Error: Invalid price!");

         try
         {
            System.out.print("Enter price: ");
            price = Double.parseDouble(in.nextLine());
         }
         catch (Exception e) { }
      }

      if (type == CD)
      {
         // Request and obtain the CD's artiste
         System.out.print("Enter artiste: ");
         String artiste = in.nextLine();

         while (artiste.trim().length() == 0)
         {
            System.out.println("Error: Invalid artiste!");
            System.out.print("Enter artiste: ");
            artiste = in.nextLine();
         }

         // Instantiate new CD product with obtained details
         newItem = new CD(title, price, artiste);
      }
      else
      {
         // Request and obtain the DVD's director
         System.out.print("Enter director: ");
         String director = in.nextLine();

         // Request and obtain the DVD's release date
         System.out.print("Enter release date (DD/MM/YYYY): ");
         String releaseDate = in.nextLine();

         // Validate the date until it is valid
         while (!validDate(releaseDate))
         {
            System.out.println("Error: invalid date!");

            // Request and obtain the DVD's release date
            System.out.print("Enter release date (DD/MM/YYYY): ");
            releaseDate = in.nextLine();
         }

         // Request and obtain the DVD's region code
         int regionCode = 0;

         try
         {
            System.out.print("Enter region code (1-5): ");
            regionCode = Integer.parseInt(in.nextLine());
         }
         catch (Exception e) { }

         // Validate the region code until it is valid
         while (regionCode < 1 || regionCode > 5)
         {
            System.out.println("Error: invalid region code!");

            // Request and obtain the DVD's region code
            try
            {
               System.out.print("Enter region code (1-5): ");
               regionCode = Integer.parseInt(in.nextLine());
            }
            catch (Exception e) { }
         }

         // Instantiate new DVD product with obtained details
         newItem = new DVD(title, price, director, releaseDate, regionCode);

         // Request and obtain the DVD's actor
         System.out.print("Enter actor (type 'exit' to finish): ");
         String actor = in.nextLine();

         // Keeping adding actors until there is no more
         while (!actor.equalsIgnoreCase("exit"))
         {
            ((DVD) newItem).addActor(actor);
            System.out.print("Enter actor (type 'exit' to finish): ");
            actor = in.nextLine();
         }
      }

      catalogue.add(newItem);

      if (type == CD)
         System.out.println("The CD has been added...");
      else
         System.out.println("The DVD has been added...");
   }

   // Method:  removeProduct
   // Purpose: To remove a product from the catalogue
   // Passed:  catalogue - array list of the products catalogue
   // Input:   obtains product number from the scanner connected to the standard-input device.
   // Output:  the prompt for input and the outcome message for the removal
   public void removeProduct(Catalogue catalogue)
   {
      System.out.println("\nPlease select a product");

      // display the catalogue
      for (int i = 0; i < catalogue.size(); i++)
      {
         Product prod = (Product) catalogue.get(i);
         System.out.println("\nProduct " + (i + 1) + ": " + "\n" +
                            prod.getDetails());   // polymorphism
      }

      // Obtain the product choice
      int choice = 0;

      try
      {
         System.out.print("\nEnter your choice (1-" + catalogue.size() + "): ");
         choice = Integer.parseInt(in.nextLine());
      }
      catch (Exception e) { }

      // Validate the choice until it is valid
      while (choice < 1 || choice > catalogue.size())
      {
         System.out.println("Error: invalid choice!");

         try
         {
            System.out.print("\nEnter your choice (1-" + catalogue.size() + "): ");
            choice = Integer.parseInt(in.nextLine());
         }
         catch (Exception e) { }
      }

      if (catalogue.remove(choice - 1) == null)
         System.out.println("Sorry! The product failed to be removed...");
      else
         System.out.println("The product has beem removed...");
   }

   // Method:  createCustomer
   // Purpose: To register a customer
   // Passed:  customer - array list of the customer
   // Input:   obtains the customerdetails
   // Output:  the prompt for input and the outcome message for the creation
   public void createCustomer(UserDatabase users)
   {
      System.out.println();
      System.out.println("-- New Customer Details --");

      System.out.print("Enter name: ");
      String name = in.nextLine();

      System.out.print("Enter address: ");
      String address = in.nextLine();

      System.out.print("Enter phone: ");
      String phone = in.nextLine();

      System.out.print("Enter email: ");
      String email = in.nextLine();

      String username = "";
      boolean valid = false;

      while (!valid)
      {
         System.out.print("Enter username: ");
         username = in.nextLine();

         if (username.length() != User.USERNAME_LENGTH)
            System.out.print("Error: Username must be " + User.USERNAME_LENGTH +
                             " characters long!");
         else if (users.contains(username))
            System.out.print("Error: Username already exists!");
         else
            valid = true;
      }

      String password = "";
      valid = false;

      while (!valid)
      {
         System.out.print("Enter password: ");
         password = in.nextLine();

         if (password.length() != User.PASSWORD_LENGTH)
            System.out.print("Error: Password must be " + User.PASSWORD_LENGTH +
                             " characters long!");
         else
            valid = true;
      }

      Customer newCustomer = new Customer(name, address, phone, email, username, password);
      users.add(newCustomer);
      System.out.println("The customer has been added...");
   }

   // Method:  getProduct
   // Purpose: To find and return a product in the catalogue
   // Passed:  productNumber - the value of the product number for search
   //          catalogue - array  list of the products catalogue
   // Returns: the Product object if the search has the result, null otherwise.
   public Product getProduct(String productNumber, ArrayList<Product> catalogue)
   {
      // find the product with productNumber
      for (int i = 0; i < catalogue.size(); i++)
      {
         Product prod = (Product) catalogue.get(i);

         if (productNumber.equals(prod.getProductNumber()))
         {
            return prod;
         }
      }

      return null;         // product number not found
   }

   // Method:  validDate
   // Purpose: To check if a date is valid
   // Passed:  date - the string of the date
   // Returns: true if it is valid; false otherwise.
   private boolean validDate(String date)
   {
      // split the date string into individual fields
      StringTokenizer st = new StringTokenizer(date, "/");

      int day = Integer.parseInt(st.nextToken());
      int month = Integer.parseInt(st.nextToken());
      int year = Integer.parseInt(st.nextToken());

      // check if the year is valid
      if (year <= 0)
         return false;

      // check if the month and day is valid
      switch (month)
      {
         case 1: case 3: case 5: case 7: case 8: case 10: case 12:   // big month
            if (day < 1 || day > 31)
               return false;
            break;
         case 4: case 6: case 9: case 11:    // small month
            if (day < 1 || day > 30)
               return false;
            break;
         case 2:
            if (isLeapYear(year))
            {
               if (day < 1 || day > 29)
                  return false;
            }
            else
            {
               if (day < 1 || day > 28)
                  return false;
            }
            break;
         default:
            return false;
      }

      return true;
   }

   // Method:  isLeapYear
   // Purpose: To check if a year is a leap year
   // Passed:  year - the value of the year
   // Returns: true if it is a leap year; false otherwise.
   private boolean isLeapYear(int year)
   {
      // the year is leap if it is divisible by 400, or
      //                     it is divisible by 4, but not by 100
      if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
         return true;
      return false;
   }
}



import java.util.Calendar;

// CLASS: Customer
// DESCRIPTION:
//    This class represents a customer in E-shopping store that sells CDs and
//    DVDs.
// AUTHOR:  Rafe Taya
// VERSION: 1 (March 20, 2007).

public class Customer extends User
{
   // Array of shopping items; a polymorphic variable
	private Product[] shoppingCart;

	// Current number of items in the shopping cart array
	private int numItems;

   // Constant maximum number of items for the shopping cart array
   private static final int MAX_ITEMS = 10;

	// Non-default Constructor
   public Customer(String name, String address, String phone, String email,
                   String username, String password)
   {
      super(name, address, phone, email, username, password);
      setType(CUSTOMER);
      shoppingCart = new Product[MAX_ITEMS];
      numItems = 0;
   }

   // Method:  getNumItems
   // Purpose: To return the number of items in the customer's shopping cart.
   // Returns: the integer representing the array size
   public int getNumItems()
   {
      return numItems;
   }

   // Method:  addProduct
   // Purpose: To add a product in the customer's shopping cart.
   // Passed:  newItem - the value of the product for addition
   // Returns: true if the addition is completed, false otherwise.
   public boolean addProduct(Product newItem)
   {
      if (numItems < MAX_ITEMS)
      {
         shoppingCart[numItems] = newItem;
         numItems++;
         return true;
      }

      return false;
   }

   // Method:  removeProduct
   // Purpose: To remove a product from the customer's shopping cart.
   // Passed:  productNumber - the value of the product number for deletion
   // Returns: true if the deletion is completed, false otherwise.
   public boolean removeProduct(String productNumber)
   {
      // find the product with productNumber
      for (int i = 0; i < numItems; i++)
      {
         if (productNumber.equals(shoppingCart[i].getProductNumber()))
         {
            shoppingCart[i] = null;

            // shift all following items backward by one position
            for (int j = i; j < numItems - 1; j++)
               shoppingCart[j] = shoppingCart[j + 1];

            numItems--;
            return true;
         }
      }

      return false;        // product number not found
   }

   // Method:  getProduct
   // Purpose: To find and return a product in the customer's shopping cart.
   // Passed:  productNumber - the value of the product number for search
   // Returns: the Product object if the search has the result, null otherwise.
   public Product getProduct(String productNumber)
   {
      for (int i = 0; i < numItems; i++)
      {
         if (productNumber.equals(shoppingCart[i].getProductNumber()))
         {
            return shoppingCart[i];
         }
      }

      return null;         // product number not found
   }

   // Method:  getProduct
   // Purpose: To retrieve a product in the customer's shopping cart.
   // Passed:  index - the value of the index of the product in the array
   // Returns: the Product object if the index is in valid range, null otherwise.
   public Product getProduct(int index)
   {
      if (index >= 0 && index < numItems)
         return shoppingCart[index];
      else
         return null;
   }

   // Method:  showSummary
   // Purpose: To display the summary of this customer to the screen, including
   //          the products in the shopping cart.
   // Output:  the summary information of the customer
   public void showSummary()
   {
      System.out.println();
      System.out.println(toString());
      System.out.println();

      showShoppingCart();
   }

   // Method:  showShoppingCart
   // Purpose: To display all products contained in the shopping cart.
   // Output:  the product information in the shopping cart
   public void showShoppingCart()
   {
      if (numItems == 0)
      {
         System.out.println("There is nothing in the shoppping cart.");
      }
      else
      {
         System.out.println("Shopping cart:");

         for (int i = 0; i < numItems; i++)
         {
            System.out.println("\nProduct " + (i + 1) + ": " + "\n" +
                               shoppingCart[i].getDetails());   // polymorphism
         }
      }
   }
}