Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 216
  • Last Modified:

Question for CEHJ-

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
LearningJava
Asked:
LearningJava
  • 11
  • 10
1 Solution
 
CEHJCommented:
I'll see what I can do. Can you post separately the class ConsoleReader?
0
 
LearningJavaAuthor Commented:
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
 
CEHJCommented:
And a sample address book file?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LearningJavaAuthor Commented:
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
 
CEHJCommented:
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
 
LearningJavaAuthor Commented:
You don't have to do the work. Just critique my code and I will make the improvements.
0
 
LearningJavaAuthor Commented:
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
 
LearningJavaAuthor Commented:
Is my documentation of the Comparator class accurate?
0
 
CEHJCommented:
>>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
 
LearningJavaAuthor Commented:
The problem I had with making variables private was that main program do longer could access them.  
0
 
CEHJCommented:
Yes, you should have accessor/mutators
0
 
LearningJavaAuthor Commented:
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
 
CEHJCommented:
>>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
 
LearningJavaAuthor Commented:
But would such methods be of use in my program?
0
 
CEHJCommented:
They would be more relevant for making your class reusable in different situations, possibly in the future.
0
 
LearningJavaAuthor Commented:
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
 
CEHJCommented:
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
 
LearningJavaAuthor Commented:
Can you elaborate?
0
 
CEHJCommented:
A phone book holds the details on more than one person
0
 
LearningJavaAuthor Commented:
But is that described by using the word people?
0
 
CEHJCommented:
>>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

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!

  • 11
  • 10
Tackle projects and never again get stuck behind a technical roadblock.
Join Now