Java Reference
In-Depth Information
// Other members as before...
}
If we want to list the entries in name sequence we have to do a little work. The keySet() method in
HashMap returns a Set object for the keys, which are Person objects, but these will not be ordered in
any way. By creating a LinkedList object from the set, we obtain a collection that we can sort using
the sort( ) method from the Collections class. Finally we get an iterator to go through the
HashMap using the keys in alphabetical order in the collection.
We can update main() to take advantage of the new features of the PhoneBook class:
class TryPhoneBook {
public static void main(String[] args) {
PhoneBook book = new PhoneBook(); // The phone book
FormattedInput in = new FormattedInput(); // Keyboard input
Person someone;
for(;;) {
System.out.println("Enter 1 to enter a new phone book entry\n"+
"Enter 2 to find the number for a name\n"+
"Enter 3 to list all the entries\n" +
"Enter 9 to quit.");
int what = 0;
try {
what = in.readInt();
} catch(InvalidUserInputException e) {
System.out.println(e.getMessage()+"\nTry again.");
continue;
}
switch(what) {
case 1:
book.addEntry(BookEntry.readEntry());
break;
case 2:
someone = Person.readPerson();
BookEntry entry = book.getEntry(someone);
if(entry == null)
System.out.println("The number for " + someone +
" was not found. ");
else
System.out.println("The number for " + someone +
" is " + book.getEntry(someone).getNumber());
break;
case 3:
book.listEntries();
break;
case 9:
book.save();
System.out.println("Ending program.");
Search WWH ::




Custom Search