Java Reference
In-Depth Information
the client will interact with the user and provide the desired name to the method—as does the client
in Listing 19-2—we could define the method as follows:
public String getPhoneNumber(Name personName)
{
return phoneBook.getValue(personName);
} // end getPhoneNumber
The method either returns a string that contains the desired telephone number or returns null if the
number is not found.
We could define a similar method instead of or in addition to the previous method, as follows:
public String getPhoneNumber(String firstName, String lastName)
{
Name fullName = new Name(firstName, lastName);
return phoneBook.getValue(fullName);
} // end getPhoneNumber
Additional methods to add or remove a person or to change a person's telephone number are
straightforward and are left as exercises.
Question 5 Implement a method for the class TelephoneDirectory that removes an entry
from the directory. Given the person's name, the method should return either the person's
telephone number or null if the person is not in the directory.
Question 6 Implement a method for the class TelephoneDirectory that changes a person's
telephone number. Given the person's name, the method should return either the person's
old telephone number or null if the person was not in the directory but has been added to it.
A Problem Solved: The Frequency of Words
Some word processors provide a count of the number of times each word occurs in a document.
Create a class FrequencyCounter that provides this capability.
19.12
This class is somewhat like the one in the previous example, so we will omit some of the design
details. Basically, the class needs to count each occurrence of a word as it reads the document
from a text file. It then needs to display the results. For example, if the text file contains
row, row, row your boat
the desired output would be
boat 1
row 3
your 1
The class will have a constructor and the methods readFile and display . As in the previ-
ous example, readFile will read the input text from a file. Then display will write the output.
Listing 19-4 shows a client of FrequencyCounter . It is similar to the beginning of the client in
the previous example.
LISTING 19-4 A client of the class FrequencyCounter
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
 
 
Search WWH ::




Custom Search