/* * Compute word frequencies for data */ import structure.*; import java.util.Scanner; public class WordFreq { // vector of associations holding words and their frequencies protected Vector wordList; // Create empty list of word frequencies public WordFreq(){ wordList = new Vector(); } // post: If word was not in frequency list it is added w/ frequency of 1, // If already present, then increase frequency by 1 public void add(String word){ for (int i = 0; i < wordList.size(); i++) { Association assoc = (Association)wordList.get(i); // check if already in list. if (assoc.getKey().equals(word)) { Integer oldValueObj = (Integer)assoc.getValue(); int oldValue = oldValueObj.intValue(); Integer newValueObj = new Integer(oldValue + 1); assoc.setValue(newValueObj); return; } } // word was not in list, insert it Association assoc = new Association(word, new Integer(1)); wordList.add(assoc); } // return string describing all words and frequencies in the list public String toString() { String answer = ""; for (int i = 0; i < wordList.size(); i++) { Association temp = (Association)wordList.get(i); answer = answer + "The word '" + temp.getKey() +"' occurs "+temp.getValue()+" times.\n"; } return answer; } public static void main(String args[]) { WordFreq list = new WordFreq(); // read input, one word at a time Scanner input = new Scanner(System.in); while (input.hasNext()) { String s = input.next(); list.add(s); } System.out.println(list); } }