/**
* A class to store names and numbers in a phone book.
* Methods for adding a name and number to the book, and
* for looking up a name, are included.
* @author Frederic Green
CS120, Fall 2007
Clark University
*/
public class PhoneBook {
//Instance variables:
//The phone book itself:
private PhoneBookRecord [] book;
//Number of entries used:
private int numberInBook;
//Capacity of the phone book:
private int maxSize;
/**
* Constructor that creates a book with at most 100 names.
*/
public PhoneBook () {
numberInBook = 0;
maxSize = 100;
book = new PhoneBookRecord[maxSize];
int i;
for (i = 0; i < maxSize; i++)
book[i] = null;
}//PhoneBook constructor
/**
* Constructor that creates a book with at most the given number
* of names.
* @param Maximum The capacity of the phone book.
*/
public PhoneBook (int maximum) {
numberInBook = 0;
maxSize = maximum;
book = new PhoneBookRecord[maxSize];
for (int i = 0; i < book.length; i++)
book[i] = null;
}//PhoneBook constructor
/**
* Method to add given name and number to the phone book.
* @param aName The name to add.
* @param aNumber The number to add.
*/
public void addToBook (String aName, String aNumber) {
if (numberInBook < maxSize) {
book[numberInBook] = new PhoneBookRecord(aName, aNumber);
numberInBook++;
}
else
System.out.println("Sorry, no one else permitted in this area code!");
}//addToBook
/**
* Method to return the number corresponding to the given name.
* @param aName The given name.
* @return A String containing the number.
*/
public String lookUp (String aName) {
int i;
for (i=0; i < numberInBook; i++)
if (aName.equals(book[i].getName()))
break;
if (i < numberInBook)
return book[i].getNumber();
else
return "Unlisted number";
}//lookUp
/**
* Method to print all the names and numbers in the book.
*/
public void printBook () {
System.out.println("Here are the names and numbers:");
System.out.println("Name\t\t\tNumber");
for (int i = 0; i < numberInBook; i++)
System.out.println(book[i]);
}
/**
* Method to sort the phone book in alphabetical order
* according to name.
*/
//The algorithm used is selection sort.
public void sort () {
int indexOfSmallest;
PhoneBookRecord temp;
for (int i=0; i < numberInBook; i++) {
indexOfSmallest = indexOfSmallest(i);
temp = book[i];
book[i] = book[indexOfSmallest];
book[indexOfSmallest] = temp;
}//for
}//sort
//Support method to find index of smallest element.
private int indexOfSmallest (int start)
{
int indexOfMinimum = start;
PhoneBookRecord smallest = book[start];
for (int i=start+1; i < numberInBook; i++)
if ((book[i].getName()).compareTo(smallest.getName()) < 0)
{
smallest = book[i];
indexOfMinimum = i;
}
return indexOfMinimum;
}//indexOfSmallest
}//PhoneBook class