Link to home
Start Free TrialLog in
Avatar of LearningJava
LearningJava

asked on

Question for CEHJ- Compartor sorting

Hi:
    I have made some changes to my code. The result is I have eliminated two Comparators and the Keyword class.

Please inspect and provide feedback?

import java.util.Comparator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
/**
@author LearningJava
A telephone lookup program.
@version 1.0
*/
public class Telephone
{  public static void main(String[] args)
   {  ConsoleReader console = new ConsoleReader(System.in);
      System.out.print ("Enter the file name where the address book"
        + " is stored: ");
      String fileName = console.readLine();
      if (fileName == null)
      System.exit(0);
     
      ArrayList  phoneList   =  new  ArrayList();              
      try
      {  FileReader fr = new FileReader(fileName);
         BufferedReader in  = new BufferedReader(fr);
         boolean more = true;
         while (more)
         {  String name = in.readLine();
            String number = null;
            if (name != null) number = in.readLine();
            if (number != null)
            {        
               phoneList.add(new PhoneBookEntry(name, number));          
            }
            else more = false;
         }
         in.close();
      }
      catch (IOException exception)
      {  
         System.out.println("An I/O error occurred while reading"  
            + fileName);
         System.exit(1);
      }      
      System.out.println("Search choice: 1)name, 2)number");
      int choice = console.readInt();
      switch(choice)
      {
      case LOOKUP_TYPE_NAME:
     
      System.out.println ("Name:");
      String name = console.readLine ();
      NameSearch forName = new NameSearch(name, phoneList);
      forName.nameSearch(name, phoneList);
      break;
      case LOOKUP_TYPE_NUMBER:
     
      System.out.println ("Number: ");
      String number = console.readLine ();
      NumberSearch forNumber = new NumberSearch(number, phoneList);
      forNumber.numberSearch(number, phoneList);
      break;      
      }
   }
   private static final int LOOKUP_TYPE_NAME = 1;
   private static final int LOOKUP_TYPE_NUMBER = 2;
}  


/**
Describes a Telephone book.
@author LearningJava
@version 1.0
*/

class PhoneBookEntry
{

   /**
   Constructor for a phonebook.
   @param name     A person's full name.
   @param number   The phone number.
   */

   public PhoneBookEntry(String name, String number)
   {
      fullName = name;
      phoneNum = number;

   }

   /**
   Method(accessor) to get full name.
   @return fullName  The full name.
   */
   public String getName()
   {
      return fullName;
   }

   /**
   Method(accessor)to get the telephone number.
   @return phoneNum  The telephone number.
   */
   public String getNumber()
   {
      return phoneNum;
   }

   /**
   Method(mutator) to alter the fullName.
   @param fullName  A person's full name.
   */
   public void setFullName(String fullName)
   {
      this.fullName = fullName;
   }

   /**
   Method(mutator)to alter the phone number.
   @param phoneNumber   The phone number.
   */
   public void setPhoneNumber(String phoneNumber)
   {
      this.phoneNum = phoneNum;
   }
   
 

   /**
   Method to return a string.
   @return The phonebook as a string.
   */

   public String toString()
   {
      return fullName + " " + phoneNum;
   }

   private String fullName;
   private String phoneNum;
 
}


/**
Describes a NameSearch.
@author LearningJava
@version 1.0
*/
class NameSearch
{  /**
   Constructor for a NameSearch.
   @param name      A name.
   @param phoneList A phoneList containing names and phone numbers.
   */
   public NameSearch(String name, ArrayList phoneList)
   {  this.name = name;
      this.phoneList = phoneList;
   
   }
   
   /**
   Method to get a name.
   @return name  The name.
   */
   public String getName()
   {
      return name;
   }
   
   /**
   Method to get a phone list.
   @return phoneList  The phone list.
   */
   public ArrayList getPhoneList()
   {
      return phoneList;
     
   }
   
   /**
   Method to find a name and corresponding phone number from a phonelist.
   @param name      The name.
   @param phoneList The phone list.
   */
    public  static void nameSearch(String name, ArrayList phoneList)
    {
       PhoneBookEntry findName = new PhoneBookEntry(name,"");
       Comparator fullName = new FullNameComp();
       Collections.sort(phoneList, fullName);
         int foundIndex = Collections.binarySearch(phoneList, findName, fullName);
       
       if (foundIndex >= 0 && foundIndex < phoneList.size())
       {
           System.out.println(phoneList.get(foundIndex));
       }
       else
       {
            System.out.println("Name:  " + findName + " not found in the phonebook");
       }      
    }  
 
   private String name;
   private ArrayList phoneList;
}


/**
Describes a NumberSearch.
@author LearningJava
@version 1.0
*/
class NumberSearch
{  /**
   Constructor for a NumberSearch.
   @param number    A number.
   @param phoneList A phoneList containing names and phone numbers.
   */
   public NumberSearch(String number, ArrayList phoneList)
   {  this.number = number;
      this.phoneList = phoneList;
   
   }
   
   /**
   Method to get a phone number.
   @return number  The number.
   */
   public String getNumber()
   {
      return number;
   }
   
   /**
   Method to get a phone list.
   @return phoneList  The phone list.
   */
   public ArrayList getPhoneList()
   {
      return phoneList;
     
   }
   
   /**
   Method to find a phone number and corresponding name from a phonelist.
   @param number    The number.
   @param phoneList The phone list.
   */
   public  static void numberSearch(String number, ArrayList phoneList)
   {  
      PhoneBookEntry findNumber = new PhoneBookEntry("",number);
      Comparator numberSort = new NumberSort();
      Collections.sort(phoneList, numberSort);
      int foundIndex = Collections.binarySearch(phoneList, findNumber, numberSort);
       
      if (foundIndex >= 0 && foundIndex < phoneList.size())
      {
         System.out.println(phoneList.get(foundIndex));
      }
      else
      {
         System.out.println("Number:  " + findNumber + " not found in the phonebook");
      }      
   }  
   
   
   
   private String number;
   private ArrayList phoneList;
   
}

/**
A class that implemements the Comparator interface for sorting
PhoneBook objects.
@author LearningJava
@version 1.0
*/
class FullNameComp implements Comparator
{

   /**
   A method that compares arguments(compareTo method of the String class)
   for natural order(ascending)based on full name.

   @param obj1 The first object.
   @param obj2  The second object.
   @return     A negative integer, zero, or a positive integer as this
               object is less than, equal to, or greater than the
               specified object.
   */
   public int compare(Object obj1, Object obj2)
   {  
      if(!(obj1 instanceof PhoneBookEntry))
        throw new ClassCastException();
      if(!(obj2 instanceof PhoneBookEntry))
        throw new ClassCastException();

      PhoneBookEntry people1 = (PhoneBookEntry) obj1;
      PhoneBookEntry people2 = (PhoneBookEntry) obj2;
      return people1.getName().compareTo(people2.getName());
   }

}



/**
A class that implemements the Comparator interface for sorting objects.
@author LearningJava
@version 1.0
*/
class NumberSort implements Comparator
{
   /**
   A method that compares arguments for natural order based on phone
   number.
   @param obj1 The first object.
   @param obj2  The second object.
   @return     A negative integer, zero, or a positive integer as this
               object is less than, equal to, or greater than the
               specified object.
   */
   public int compare(Object obj1, Object obj2)
   {  
       if(!(obj1 instanceof PhoneBookEntry))
        throw new ClassCastException();
      if(!(obj2 instanceof PhoneBookEntry))
        throw new ClassCastException();
               
      PhoneBookEntry number1 = (PhoneBookEntry) obj1;
      PhoneBookEntry number2 = (PhoneBookEntry) obj2;
      return number1.getNumber().compareTo(number2.getNumber());
   }

}





Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

That's very good. You clearly followed through on my last two questions regarding the Comparators. Just two points

1. For the unused field as in

>>PhoneBookEntry findNumber = new PhoneBookEntry("",number);

it would be even better to use null (test this just in case), as "" will create a redundant String

>>PhoneBookEntry findNumber = new PhoneBookEntry(null, number);

2. What made you do the second test here?

if (foundIndex >= 0 && foundIndex < phoneList.size())

Is this all your own work? ;-)
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> The result is I have eliminated two Comparators and the Keyword class.

Good to hear, I mentioned that a few questions ago that your Keyword class served no real purpose :-)
Avatar of LearningJava
LearningJava

ASKER

I appreciate your input.

Thanks.