import java.io.*; import java.util.*; // Rhys Price Jones October 2005 // Demonstates some cool new Java 1.5 features // Scanner for input // auto boxing-unboxing for int-Integer // generics to make a HashMap // enhanced for-loop to go through the whole HashMap public class CountWords { final static int HASHSIZE = 20000; public static void main(String[] args) { if (args.length < 1) { System.err.println("I need a file"); System.exit(-1); } Scanner sc = null; try {sc = new Scanner(new File(args[0]));} catch(FileNotFoundException fnfe) { System.err.println("No such file"); System.exit(-1); } String s; Map c = new HashMap(HASHSIZE); while (sc.hasNext()) { s = (sc.next()).toLowerCase(); if (c.get(s) == null) c.put(s,1); // auto boxing else c.put(s, 1+c.get(s)); // auto boxing-unboxing } for (String key : c.keySet()) { System.out.println(key+" appears "+c.get(key)+" times"); } } }