Java Reference
In-Depth Information
Programming Tip: When using a Scanner object to process text, any character can be a
delimiter if it does not occur in any desired token. You create a string of these delimiters using a
special notation and give it to the Scanner method useDelimiter . Consult Segment A.82 of
Appendix A for more details.
19.16
The following implementation of the method readFile reflects the previous discussion:
/** Reads a text file of words and counts their frequencies
of occurrence.
@param data a text scanner for the text file of data */
public void readFile(Scanner data)
{
data.useDelimiter("\\W+");
while (data.hasNext())
{
String nextWord = data.next();
nextWord = nextWord.toLowerCase();
Integer frequency = wordTable.getValue(nextWord);
if (frequency == null )
{ // add new word to table
wordTable.add(nextWord, new Integer(1));
}
else
{ // increment count of existing word; replace wordTable entry
frequency++;
wordTable.add(nextWord, frequency);
} // end if
} // end while
data.close();
} // end readFile
Question 7 The previous method readFile does not call contains to see whether a word
is already in the dictionary, but instead calls getValue . Why did we do this?
19.17
Displaying the dictionary. Now that we have created the dictionary, we need to display the results.
An iteration of the search keys will produce the words in alphabetical order. A parallel iteration of
the values provides the corresponding frequencies. The following method is a possible solution for
this task:
public void display()
{
Iterator<String> keyIterator = wordTable.getKeyIterator();
Iterator<Integer> valueIterator = wordTable.getValueIterator();
while (keyIterator.hasNext())
{
System.out.println(keyIterator.next() + " " +
valueIterator.next());
} // end while
} // end display
Question 8 Implement a second method display for the class FrequencyCounter that dis-
plays only words that occur with a frequency given as the method's sole parameter.
 
Search WWH ::




Custom Search