// CSE 143, winter 2012 // 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 words = new HashMap(); System.out.println("Reading file..."); Scanner input = new Scanner(new File("mobydick.txt")); while (input.hasNext()) { String word = input.next(); if(words.containsKey(word)) { words.put(word, words.get(word) + 1); } else { words.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 " + words.get(word) + " times."); } } }