// CSE 143, Winter 2011, Marty Stepp // This program counts the occurrences of words in a large file and lets the // user ask how many times a given word occurred in the file. // It demonstrates the use of a Map collection. import java.io.*; import java.util.*; public class WordCount2 { public static void main(String[] args) throws FileNotFoundException { // store a mapping from each word (key) to a count of the number of // occurrences of that word seen so far (value) Map counts = new TreeMap(); System.out.println("Reading file..."); Scanner input = new Scanner(new File("mobydick.txt")); while (input.hasNext()) { String word = input.next(); if (counts.containsKey(word)) { counts.put(word, counts.get(word) + 1); } else { counts.put(word, 1); } } // prompt user for a word, and show the count of occurrences of it while (true) { Scanner console = new Scanner(System.in); System.out.print("Word to search for (blank to quit)? "); String word = console.nextLine(); if (word.equals("")) { break; } // show occurrences of word using the map System.out.println(word + " occurs " + map.get(word) + " times."); } } }