Java Reference
In-Depth Information
The method readFile must read each of these strings. Recall that the main method in Listing 19-2
in Segment 19.8 creates a scanner for the file and passes it to readFile . Using Scanner 's method
next , readFile can read each string in a line of data and assign them, respectively, to the variables
firstName , lastName , and phoneNumber . The following Java statements, then, will add the desired
entry to the dictionary phoneBook :
Name fullName = new Name(firstName, lastName);
phoneBook.add(fullName, phoneNumber);
We assume that the text file contains distinct names.
Here is the definition of readFile :
/** Reads a text file of names and telephone numbers.
@param data a text scanner for the text file of data */
public void readFile(Scanner data)
{
while (data.hasNext())
{
String firstName = data.next();
String lastName = data.next();
String phoneNumber = data.next();
Name fullName = new Name(firstName, lastName);
phoneBook.add(fullName, phoneNumber);
} // end while
data.close();
} // end readFile
Using Scanner 's methods hasNext and next , we extract each name and telephone number as
strings from the text file. Then, using the two statements we examined earlier, we create a Name
object and add it and the telephone number to the dictionary.
Programming Tip: java.util.Scanner
The class Scanner enables you to break a string into substrings, or tokens , that are separated
by characters called delimiters . By default, white-space characters are the delimiters. You
pass to Scanner 's constructor either the string to be parsed or a text file represented as an
instance of the class java.io.File .
The following methods in the class Scanner enable you to extract the tokens from any
string:
public String next();
public boolean hasNext();
Appendix A discusses Scanner in more detail, beginning at Segment A.81.
Question 4 Although the statement
directory.readFile(data);
is inside a try block near the beginning of the method main in Listing 19-2, it need not be. Explain
its present location, why it can appear outside of a try block, and what you can do to move it.
19.11
A method that searches. The class TelephoneDirectory has a method to find a person's tele-
phone number. This method needs the person's name, and the user must supply it. If we assume that
Search WWH ::




Custom Search