?
Solved

Question for CEHJ- Compartor sorting

Posted on 2003-03-14
4
Medium Priority
?
233 Views
Last Modified: 2010-05-18
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());
   }

}





0
Comment
Question by:LearningJava
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 8139553
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? ;-)
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 1400 total points
ID: 8139578
You've called your Comparators FullNameComp and NumberSort. Why not make the naming convention symmetrical? Using the principle of self-documentation, i would suggest CompareOnFullName and CompareOnNumber.
0
 
LVL 92

Expert Comment

by:objects
ID: 8139869
> 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 :-)
0
 

Author Comment

by:LearningJava
ID: 8140920
I appreciate your input.

Thanks.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month8 days, 8 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question