Java Reference
In-Depth Information
The first two highlighted lines in the
main
method of Listing 19-2 perform these steps. Given the
name
data.txt
of the text file,
main
creates a scanner for the file and passes it to
readFile
. Note
the exceptions that might occur in creating the scanner. If you need more information about either
exceptions or files, consult Appendices E and F, respectively.
After the file is read,
main
interacts with the user via the private method
getName
. Each name read
from the user is passed to the method
getPhoneNumber
, where it will be the key in a search of the tele-
phone directory. Notice how
getName
uses
Scanner
to both read the user's input and then process it.
LISTING 19-2
A client of the class
TelephoneDirectory
import
java.util.Scanner;
import
java.io.File;
import
java.io.FileNotFoundException;
import
java.io.IOException;
public class
Driver
{
private static final
Name INPUT_ERROR =
new
Name("error", "error");
private static final
Name QUIT =
new
Name("quit", "quit");
public static void
main(String[] args)
{
TelephoneDirectory directory =
new
TelephoneDirectory();
String fileName = "data.txt";
// or file name could be read
try
{
Scanner data =
new
Scanner(
new
File(fileName));
directory.readFile(data);
}
catch
(FileNotFoundException e)
{
System.out.println("File not found: " + e.getMessage());
}
catch
(IOException e)
{
System.out.println("I/O error " + e.getMessage());
}
Name nextName = getName();
// get name for search from user
while
(!nextName.equals(QUIT))
{
if
(nextName.equals(INPUT_ERROR))
System.out.println("Error in entering name. Try again.");
else
{
String phoneNumber = directory.getPhoneNumber(nextName);
if
(phoneNumber ==
null
)