Java Reference
In-Depth Information
public Concordance()
{
wordTable =
new SortedDictionary<String, ListWithIteratorInterface<Integer>>();
} // end default constructor
/** Reads a text file of words and creates a concordance.
@param data a text scanner for the text file of data */
public void readFile(Scanner data)
{
. . . < See Segment 19.20. >
} // end readFile
/** Displays words and the lines in which they occur. */
public void display()
{
. . . < See Segment 19.21. >
} // end display
} // end Concordance
19.20
The method readFile . The method readFile reads the text file and uses the dictionary wordTable
to create the concordance. Since we must record the line number of each word, we read the file a line
at a time. We process all the words in a line before moving on to the next line. Thus, the following
definition of readFile contains two loops that are nested. The outer loop uses the scanner passed to
the method as an argument to read lines from the file. The inner loop uses another scanner to extract
the words from a line as soon as it is read. The class LinkedListWithIterator from Segment 15.19
of Chapter 15 is used to form each list of line numbers.
public void readFile(Scanner data)
{
int lineNumber = 1;
while (data.hasNext())
{
String line = data.nextLine();
line = line.toLowerCase();
Scanner lineProcessor = new Scanner(line);
lineProcessor.useDelimiter("\\W+");
while (lineProcessor.hasNext())
{
String nextWord = lineProcessor.next();
ListWithIteratorInterface<Integer> lineList =
wordTable.getValue(nextWord);
if (lineList == null )
{ // create new list for new word; add list and word to index
lineList = new LinkedListWithIterator<Integer>();
wordTable.add(nextWord, lineList);
} // end if
// add line number to end of list so list is sorted
lineList.add(lineNumber);
} // end while
Search WWH ::




Custom Search