Java Reference
In-Depth Information
Of course, you can try it with several entries if you have the stamina.
How It Works
The values in the map that represents a phone book are BookEntry objects to allow for more information
to be stored about a person. If you wanted to keep it really simple, you could use PhoneNumber objects
as values in the map.
The main() method runs an ongoing loop that continues 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 is added to the HashMap member of the PhoneBook object.
If a 2 is entered, the getEntry() method is called. The readPerson() member of the Person class is
called 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 is returned, so you have to check for it and display an appropriate message.
String comparisons are case sensitive so searching for “algernon lickspittle" will not find an entry. You
could convert both strings to the same case if you wanted to have comparisons that were not case sensit-
ive.
TRY IT OUT: Storing a Map in a File
This phone book is not particularly useful. The process of echoing what you just keyed in doesn't hold
one's interest for long. What you need is a phone book that is held in a file. That's not difficult. You just
need to add a constructor and another method to the PhoneBook class:
import java.nio.file.*;
import java.io.*;
import java.util.*;
class PhoneBook implements Serializable {
public PhoneBook() {
if(Files.exists(file)) {
// If there's a phone
book in a file...
try (ObjectInputStream in = new ObjectInputStream(
new
BufferedInputStream(Files.newInputStream(file)))){
phonebook = (HashMap<Person, BookEntry>)in.readObject();
//...read it in.
} catch(ClassNotFoundException| IOException e) {
e.printStackTrace();
System.exit(1);
}
Search WWH ::




Custom Search