// Textbook fragment 09.06 import java.io.*; import java.util.*; /** A program that counts words in a document, printing the most frequent. */ public class WordCount { public static void main(String[] args) throws IOException { Scanner cin = new Scanner(System.in); cin.useDelimiter("[^a-zA-Z]"); // ignore non-letters HashTableMap h = new HashTableMap(); String word; Integer count; while (cin.hasNext()) { word = cin.next(); if (word.equals("")) continue; // ignore null strings between delimiters word = word.toLowerCase(); // ignore case count = h.get(word); // get the previous count for this word if (count == null) h.put(word, 1); else h.put(word, ++count); } int maxCount = 0; String maxWord = "no word"; for (Entry ent : h.entrySet()) { // find max-count word if (ent.getValue() > maxCount) { maxWord = ent.getKey(); maxCount = ent.getValue(); } } System.out.print("The most frequent word is \"" + maxWord); System.out.println(",\" with word-count = " + maxCount + "."); } }