// 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)); } } // post: returns a Map where the keys are the unique words in the input file // and the 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(); // Two cases: // 1. the first time we see a key // 2. we've seen this key before if (!wordCounts.containsKey(word)) { wordCounts.put(word, 1); } else { wordCounts.put(word, wordCounts.get(word) + 1); /* // Can also write it this two line way int oldCount = wordCounts.get(word); wordCounts.put(word, oldCount + 1); */ } /* // Another way to write the code above // One case for the first time we see the word, and // a general case we run every time if (!wordCounts.contains(word)) { wordCounts.put(word, 0); } wordCounts.put(word, wordCounts.get(word) + 1); */ } return wordCounts; } }