1234567891011121314151617181920212223242526272829303132333435
  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.util.Map;
  4. import java.util.Scanner;
  5. import java.util.TreeMap;
  6. public class SimpleWordCounter {
  7. public static void main(String[] args) {
  8. try {
  9. File f = new File("ciaFactBook2008.txt");
  10. Scanner sc;
  11. sc = new Scanner(f);
  12. // sc.useDelimiter("[^a-zA-Z']+");
  13. Map<String, Integer> wordCount = new TreeMap<String, Integer>();
  14. while(sc.hasNext()) {
  15. String word = sc.next();
  16. if(!wordCount.containsKey(word))
  17. wordCount.put(word, 1);
  18. else
  19. wordCount.put(word, wordCount.get(word) + 1);
  20. }
  21. // show results
  22. for(String word : wordCount.keySet())
  23. System.out.println(word + " " + wordCount.get(word));
  24. System.out.println(wordCount.size());
  25. }
  26. catch(IOException e) {
  27. System.out.println("Unable to read from file.");
  28. }
  29. }
  30. }