// Hunter Schafer, CSE 143 // This program calculates the number of times each word appears in a file import java.io.*; import java.util.*; public class WordCounter { public static void main(String[] args) throws FileNotFoundException { System.out.println("Reading file..."); Scanner input = new Scanner(new File("mobydick.txt")); Map wordCounts = countWords(input); for (String word : wordCounts.keySet()) { System.out.println(word + " " + wordCounts.get(word)); } } // pre : Scanner is not null // post: Returns a Map whose keys are words in the input file and whose // values are the number of times that word appeared in the file public static Map countWords(Scanner input) { Map wordCounts = new TreeMap(); while (input.hasNext()) { String word = input.next(); if (!wordCounts.containsKey(word)) { wordCounts.put(word, 1); } else { wordCounts.put(word, wordCounts.get(word) + 1); } } return wordCounts; } }