import java.awt.Font; import java.io.File; import java.io.IOException; import java.util.Comparator; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * * @author Bill Kraynek */ public class CountWordsWithMaps { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { Scanner fileScanner = new Scanner(new File("src/CountWordsWithMaps.java")); fileScanner.useDelimiter("[^A-Za-z]+"); Map words = new TreeMap(new IgnoreCaseComparator()); int maxWordLength = 25; while (fileScanner.hasNext()) { String word = fileScanner.next(); if (!words.keySet().contains(word)) { words.put(word, 0); }// end if words.put(word, words.get(word) + 1); }// end while display(words, maxWordLength); Map words1 = new TreeMap(new CountWordsComparator(words)); words1.putAll(words); display(words1, maxWordLength); String[] wordsArray = words.keySet().toArray(new String[0]); while (true) { String word = (String) JOptionPane.showInputDialog(null, "Pick a Word", "Words and Counts", JOptionPane.PLAIN_MESSAGE, null, wordsArray, wordsArray[0]); if (word == null) { return; } JOptionPane.showMessageDialog(null, word + " appeared " + words.get(word) + " time(s)."); } } static void display(Map words, int maxWordLength) { String blanks = ""; for (int i = 0; i < maxWordLength + 1; i++) { blanks += " "; } String out = " Word" + blanks.substring(8) + "Count\n\n"; for (String word : words.keySet()) { out += word + blanks.substring(word.length()) + words.get(word) + "\n"; }// end for JTextArea outArea = new JTextArea(out, 40, 30); outArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 15)); JOptionPane.showMessageDialog(null, new JScrollPane(outArea)); } static class CountWordsComparator implements Comparator { private Map words; public CountWordsComparator(Map words) { this.words = words; }// end constructor public int compare(String lhs, String rhs) { int countDifference = words.get(rhs) - words.get(lhs); if (countDifference != 0) { return countDifference; } return lhs.compareTo(rhs); } }// end WordCountComparator static class IgnoreCaseComparator implements Comparator { public int compare(String lhs, String rhs) { return lhs.compareToIgnoreCase(rhs); } } }