import structure.*; import com.mw.io.*; import java.io.*; // This variation of the WordFreq program takes its input from a text file, // whose name is provided as the parameter args[0]. Note that the ReadStream // r is linked to the FileInputStream object istream, which is initialized to // that file name via args[0]. public class WordFreqSort { //+implementation public static void main(String args[]) { Vector vocab = new Vector(1000); int i; try { InputStream istream = new FileInputStream(args[0]); ReadStream r = new ReadStream(istream); // for each word on input for (r.skipWhite(); !r.eof(); r.skipWhite()) { Association wordInfo; // word-frequency association String vocabWord; // word in the list // read in and tally instance of a word String word = r.readString(); for (i = 0; i < vocab.size(); i++) { // get the association wordInfo = (Association)vocab.elementAt(i); // get the word from the association vocabWord = (String)wordInfo.key(); if (vocabWord.equals(word)) { // match: increment integer in association Integer f = (Integer)wordInfo.value(); wordInfo.setValue(new Integer(f.intValue() + 1)); break; } } // mismatch: insert new word at position 0, with frequency 1. if (i == vocab.size()) { vocab.insertElementAt( new Association(word,new Integer(1)), 0); } } } catch (IOException e) { System.err.println(e); return; } // remove all the elements that occur once for (i = 0; i < vocab.size(); i++) { if (((Integer)(((Association)vocab.elementAt(i)).value())).intValue() == 1) vocab.removeElementAt(i); } // sort vector by frequency VectorInsertionSort.insertionSort(vocab, vocab.size()); // print out the accumulated word frequencies for (i = 0; i < vocab.size(); i++) { Association wordInfo = (Association)vocab.elementAt(i); System.out.println( wordInfo.key()+" occurs "+ wordInfo.value()+" times."); } } //-implementation }