import java.io.*; import java.util.*; public class WordFreq { Hashtable map = new Hashtable(); //open the file and populate the map with words and their counts public void count(String filename) { File f = new File(filename); Scanner sc = null; try { sc = new Scanner(f); } catch (FileNotFoundException e) { System.out.println("cannot open scanner"); System.exit(1); }; while (sc.hasNext()) { //System.out.println("next word is: " + sc.next()); //the current word String word = sc.next(); if (map.containsKey(word)) { //increment frequency int freq = (int)map.get(word); map.put(word, (Integer)(freq+1)); } else { //insert this new word with frequency=1 map.put(word, (Integer)1); } }//while System.out.println("done counting"); } //count //prints the words in map and their frequencies public void print() { Set set = map.keySet(); Object[] words = set.toArray(); Arrays.sort(words); for (Object s:words) { //get the frequency from the map int freq = (int)map.get(s); System.out.println(s + ": " + freq); } } //prints the words in map and their frequencies public void print2() { //the entries in the map are Map.Entry Set > set = map.entrySet(); //i tried to force words t obe an array of //Map.Entry, but i did not manage Object [] words = set.toArray(); //we want to sort Map.Entry. The "standard" //sort does not work because there is no natual ordering //defined on this type of objects. We have to sort using a //comparator. MyEntryComparator compobj = new MyEntryComparator(); Arrays.sort(words, compobj); //print the for (Object s:words) { System.out.println(s); } } public static void main(String[] args) { if (args.length != 1) { System.out.println("usage: WordFreq "); System.exit(1); } WordFreq obj = new WordFreq(); obj.count(args[0]); obj.print2(); } } //compares entries in the map, using the key class MyEntryComparator implements Comparator{ public int compare (Object o1, Object o2) { //map the objects to entries in the map Map.Entry e1, e2; e1 = (Map.Entry) o1; e2 = (Map.Entry) o2; //grab teh string in the entry String s1, s2; s1 = e1.getKey(); s2 = e2.getKey(); return s1.compareTo(s2); } //is this ok empty? public boolean equals(Object obj) { return false;} }