?
Solved

Question for CEHJ-

Posted on 2003-03-06
21
Medium Priority
?
212 Views
Last Modified: 2012-03-15
Hi:
   Could you have a look at the following Telephone program. The program works but I need someone inspect it and indicate shortcomings and indicate how and why I should rework it.

Thanks.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.Arrays;
/**
@author Somebody
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);
      int arraySize = 8;
      PhoneBook people [] = new PhoneBook[arraySize];
         
      try
      {  FileReader fr = new FileReader(fileName);
         BufferedReader in  = new BufferedReader(fr);
         boolean more = true;
         int count = 0;
         while (more && count < people.length)
      {  
         String k = in.readLine();
         String v = null;
         if (k != null) v = in.readLine();
         if (v != null)
         {  
            people[count] = new PhoneBook(k, v);
            count++;
         }
         else more = false;
      }
         
              in.close();
               
      }
      catch (IOException exception)
      {  
         System.out.println(exception);
         System.exit(1);
      }
                 
      System.out.println("Search choice: 1)name, 2)number");
      String choice = console.readLine ();
     
      if (choice.equals("1"))
      {        
         System.out.println ("Name:");
         String name = console.readLine ();
         Comparator fullName = new FullNameComp();
     
         Arrays.sort(people, fullName);
         Keyword kw = new Keyword(name);
         Comparator nameLookup = new NameLookup();  
         int foundIndex = Arrays.binarySearch(people, kw, nameLookup);

        if (foundIndex >= 0)
        {
           System.out.println(people[foundIndex]);
        }
        else
        {
           System.out.println("Name:  " + kw + "' not found in the phonebook");
        }
           
      }
     
      if (choice.equals("2"))
      {
        System.out.println ("Number:");
        String phoneNumber = console.readLine ();
        Comparator numSort = new NumberSort();
        Arrays.sort(people, numSort);
       
        Keyword kw2 = new Keyword(phoneNumber);
        Comparator numLookup = new ReverseLookup();
        int foundIndex2 = Arrays.binarySearch(people, kw2, numLookup);
       
        if (foundIndex2 >= 0)
        {
           System.out.println(people[foundIndex2]);
        }
        else
        {
           System.out.println("Number:  " + kw2 + "' not found in the phonebook");
        }
           
      }
           
     System.exit(0);

   }
}  


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

class PhoneBook
{

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

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

}


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

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

public String fullName;
public String phoneNum;

}


/**
Describes a Keyword.
@version 1.0
*/
class Keyword
{

/**
Constructor for a Keyword.
@param key The keyword.
*/
public Keyword(String key)
{

   this.key = key;

}

/**
Method to get keyword.
@return key  The keyword.
*/
public String getKey()
{
    return key;
}

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

public String toString()
{
    return key;
}
 
private String key;

}


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

{

/**
A method that compares arguments for natural order 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)
{
   PhoneBook people1 = (PhoneBook) obj1;
   PhoneBook people2 = (PhoneBook) obj2;
   return people1.fullName.compareTo(people2.fullName);
}

}


/**
A class that implemements the Comparator interface for sorting objects.
@author Somebody
@version 1.0
*/
class NameLookup implements Comparator
{
/**
A method that compares arguments for natural order.
@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)
{
    PhoneBook phonebook = (PhoneBook) obj1;
    Keyword keyword = (Keyword) obj2;
    return (phonebook.fullName).compareTo(keyword.getKey());
   
}

}


/**
A class that implemements the Comparator interface for sorting objects.
@author Somebody
@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)
{
   PhoneBook people1 = (PhoneBook) obj1;
   PhoneBook people2 = (PhoneBook) obj2;
   return people1.phoneNum.compareTo(people2.phoneNum);
}

}


/**
A class that implemements the Comparator interface for sorting objects.
@author Somebody
@version 1.0
*/
class ReverseLookup implements Comparator
{
/**
A method that compares arguments for natural order.
@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)
{
    PhoneBook phonebook = (PhoneBook) obj1;
    Keyword keyword = (Keyword) obj2;
    return (phonebook.phoneNum).compareTo(keyword.getKey());
   
}

}



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
  • 11
  • 10
21 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 8080218
I'll see what I can do. Can you post separately the class ConsoleReader?
0
 

Author Comment

by:LearningJava
ID: 8080250
Sure can.

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;

/**
   A class to read strings and numbers from an input stream.
   This class is suitable for beginning Java programmers.
   It constructs the necessary buffered reader,
   handles I/O exceptions, and converts strings to numbers.
*/

public class ConsoleReader
{  /**
      Constructs a console reader from an input stream
      such as System.in
      @param inStream an input stream
   */
   public ConsoleReader(InputStream inStream)
   {  reader = new BufferedReader
         (new InputStreamReader(inStream));
   }
   
   /**
      Reads a line of input and converts it into an integer.
      The input line must contain nothing but an integer.
      Not even added white space is allowed.
      @return the integer that the user typed
   */
   public int readInt()
   {  String inputString = readLine();
      int n = Integer.parseInt(inputString);
      return n;
   }
   
   /**
      Reads a line of input and converts it into a floating-
      point number. The input line must contain nothing but
      a nunber. Not even added white space is allowed.
      @return the number that the user typed
   */
   public double readDouble()
   {  String inputString = readLine();
      double x = Double.parseDouble(inputString);
      return x;
   }
   
   /**
      Reads a line of input. In the (unlikely) event
      of an IOException, the program terminates.
      @return the line of input that the user typed, null
      at the end of input
   */
   public String readLine()
   {  String inputLine = "";

      try
      {  inputLine = reader.readLine();
      }
      catch(IOException e)
      {  System.out.println(e);
         System.exit(1);
      }

      return inputLine;
   }

   private BufferedReader reader;
}


0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8080377
And a sample address book file?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:LearningJava
ID: 8081446
Here is the address file:

Abbott, Amy
408-924-1669
Apeyta, Ric
408-924-2185
Abrams, Arthur
408-924-6120
Axriam-Yago, Kathy
408-924-3159
Accardo, Dan
408-924-2236
Acevedo, Elvira
408-924-5200
Acevedo, Gloria
408-924-6556
joe, mac
900-000-0000

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8082018
First thing i'd probably do is make the menu a bit neater. You use print for the file entry but println elsewhere. I'd stick to print. Also, the user should be told how to enter the search criteria. There should be an option to list the entries too.
0
 

Author Comment

by:LearningJava
ID: 8082292
You don't have to do the work. Just critique my code and I will make the improvements.
0
 

Author Comment

by:LearningJava
ID: 8084183
If I made the following variables private how would use accessor methods to obtain the information about the variables for use in the telephone program?

private String fullName;
privagte String phoneNum;

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

class PhoneBook
{

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

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

}


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

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

public String fullName;
public String phoneNum;

}


0
 

Author Comment

by:LearningJava
ID: 8084194
Is my documentation of the Comparator class accurate?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8087645
>>If I made the following variables private

In the usual way:


private String fullName;


public String getFullName() {
  return fullName;
}

// and mutator

public void setFullName(String fullName) {
  this.fullName = fullName;
}

I'll double check about the doc conventions. While I'm doing that, you should have some comment (not too technical) about what's going on in the cast.

If nobody's answered your separately posted question about the doc, ask for it to be removed and get your points back - i'll answer it here.



0
 

Author Comment

by:LearningJava
ID: 8089360
The problem I had with making variables private was that main program do longer could access them.  
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8089481
Yes, you should have accessor/mutators
0
 

Author Comment

by:LearningJava
ID: 8094375
I revised my code:

1)public varibles are now private

2)PhoneBook class now accessor methods

But why do I need mutator methods and how are they used?

public void setFullName(String fullName) {
 this.fullName = fullName;
}



0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8094391
>>But why do I need mutator methods and how are they used?

These are to protect direct access to the variables and to provide a layer of indirection, which allows *how* the variables are set to change, whilst leaving clients of the class unaffected by the change of how these are set. Normally used by clients outside the package.
0
 

Author Comment

by:LearningJava
ID: 8094490
But would such methods be of use in my program?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8094528
They would be more relevant for making your class reusable in different situations, possibly in the future.
0
 

Author Comment

by:LearningJava
ID: 8094801
Would the following be an improvement to my code?

/**
A class that implemements the Comparator interface for sorting objects.
@author John J. Farrell
@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 String))
        throw new ClassCastException();
    if(!(obj2 instanceof String))
        throw new ClassCastException();
       
   PhoneBook people1 = (PhoneBook) obj1;
   PhoneBook people2 = (PhoneBook) obj2;
   return people1.getNumber().compareTo(people2.getNumber());
}

}

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8094830
Well the first thing that should be said is that PhoneBook is not really a phone book is it? It's more of a phone book entry.
0
 

Author Comment

by:LearningJava
ID: 8094842
Can you elaborate?
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 1800 total points
ID: 8094866
A phone book holds the details on more than one person
0
 

Author Comment

by:LearningJava
ID: 8094998
But is that described by using the word people?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8102033
>>But is that described by using the word people?

Well, if it *is*, it's contradictory isn't it, as it isn't 'people' it's one person! It should be called PhoneBookEntry and PhoneBook should be a collection of PhoneBookEntries (see my posting in your other, more recent, question).
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month14 days, 16 hours left to enroll

770 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