Java Reference
In-Depth Information
238
Enter the number:
6778
Enter 1 to enter a new phone book entry
Enter 2 to find the number for a name
Enter 9 to quit.
2
Enter first name:
Slim
Enter surname:
"Pickens"
The number for Slim Pickens is 914 238 6778
Enter 1 to enter a new phone book entry
Enter 2 to find the number for a name
Enter 9 to quit.
9
Ending program.
Of course, you can try it with several entries if you have the stamina.
How It Works
The main() method runs an ongoing loop that will continue until a 9 is entered. When a 1 is entered,
the addEntry() method for the PhoneBook object is called with the expression
BookEntry.readEntry() as the argument. The static method readEntry() calls the static
methods in the Person class and the PhoneNumber class to read from the keyboard and create objects
of these classes. The readEntry() method then passes these objects to the constructor for the
BookEntry class, and the object that is created is returned. This object will be added to the HashMap
member of the PhoneBook object.
If a 2 is entered, the getEntry() method is called. The argument expression calls the
readPerson() member of the Person class to obtain the Person object corresponding to the name
entered from the keyboard. This object is then used to retrieve an entry from the map in the
PhoneBook object. Of course, if there is no such entry null will be returned, so we have to check for
it and act accordingly.
Storing a Map in a File
This phone book is not particularly useful. The process of echoing what we just keyed in doesn't hold
one's interest for long. What we need is a phone book that is held in a file. That's not difficult. We just
need to add a constructor and another method to the PhoneBook class:
import java.util.*;
import java.io.*;
class PhoneBook implements Serializable {
public PhoneBook() {
if(filename.exists())
try {
ObjectInputStream in = new ObjectInputStream(
new FileInputStream(filename));
Search WWH ::




Custom Search