import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Scanner; public class WordCount { public static void main(String[] args) throws IOException { PrintStream output = System.out; if (args.length == 0) { output.println("Missing file name!"); System.exit(1); } Map wordCount = new HashMap(); Scanner fInput = new Scanner(new File(args[0])); while (fInput.hasNext()) { String word = fInput.next().toLowerCase(); // remove punctuation // (except for hyphens and apostrophes) String regex = "[^a-z-']"; word = word.replaceAll(regex, ""); // is word already in the map? Integer count = wordCount.get(word); if (count == null) { wordCount.put(word, 1); } else { wordCount.put(word, count + 1); } } // get the set of words in the map Set words = wordCount.keySet(); // for each word in words for (String word : words) { output.printf("%-15s", word); Integer count = wordCount.get(word); output.println(" " + count); } } }