// This program reads in a text reads a text file specified by the user // and tracks the total number of words, number of unique words, and // number of appearances of each word in the file. It then reports all // the frequencies of all words appearing more than a minimum number of // times specified by the user. import java.util.*; import java.io.*; public class WordCount { public static void main(String[] args) throws FileNotFoundException { // open the text file Scanner console = new Scanner(System.in); System.out.print("Input file? "); String fileName = console.nextLine(); Scanner input = new Scanner(new File(fileName)); // track and count words. List allWords = new ArrayList(); Set uniqueWords = new TreeSet(); Map wordCounts = new TreeMap(); while (input.hasNext()) { String word = input.next().toLowerCase(); allWords.add(word); uniqueWords.add(word); if (wordCounts.containsKey(word)){ wordCounts.put(word, wordCounts.get(word) + 1); } else { wordCounts.put(word, 1); } } System.out.println("File has " + allWords.size() + " words."); // System.out.println(" " + allWords); System.out.println("File has " + uniqueWords.size() + " unique words."); // System.out.println(" " + uniqueWords); // System.out.println("Word counts: "); // System.out.println(" " + wordCounts); // output frequencies above a given minimum System.out.print("Minimum count? "); int min = console.nextInt(); for (String word : wordCounts.keySet()) { int count = wordCounts.get(word); if (count >= min) { System.out.println(" " + word + ": " + count); } } } }