Java Reference
In-Depth Information
MaxWords denotes the maximum number of distinct words catered for. For testing the program, we have used
50 for this value. If the number of distinct words in the passage exceeds MaxWords (50, say), any words after the 50 th
will be read but not stored, and a message to that effect will be printed. However, the count for a word already stored will
be incremented if it is encountered again.
These ideas are implemented as shown in Program P2.4.
Program P2.4
import java.io.*;
import java.util.*;
public class P2_4WordFrequency {
final static int MaxWords = 50;
public static void main(String[] args) throws IOException {
WordInfo[] wordTable = new WordInfo[MaxWords];
FileReader in = new FileReader("passage.txt");
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
for (int h = 0; h < MaxWords; h++) wordTable[h] = new WordInfo("", 0);
int numWords = 0;
String word = getWord(in).toLowerCase();
while (!word.equals("")) {
int loc = binarySearch(word, wordTable, 0, numWords-1);
if (word.compareTo(wordTable[loc].word) == 0) wordTable[loc].incrFreq();
else //this is a new word
if (numWords < MaxWords) { //if table is not full
addToList(word, wordTable, loc, numWords-1);
++numWords;
}
else out.printf("'%s' not added to table\n", word);
word = getWord(in).toLowerCase();
}
printResults(out, wordTable, numWords);
in.close();
out.close();
} //end main
public static int binarySearch(String key, WordInfo[] list, int lo, int hi) {
//search for key from list[lo] to list[hi]
//if found, return its location;
//if not found, return the location in which it should be inserted
//the calling program will check the location to determine if found
while (lo <= hi) {
int mid = (lo + hi) / 2;
int cmp = key.compareTo(list[mid].word);
if (cmp == 0) return mid; // search succeeds
if (cmp < 0) hi = mid -1; // key is 'less than' list[mid].word
else lo = mid + 1; // key is 'greater than' list[mid].word
}
Search WWH ::




Custom Search