wordCount pseudo code .java 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // importing the java package that contains each class you would like to use
  2. import java.io.IOException;
  3. import java.util.Map;
  4. import java.util.Scanner;
  5. import java.util.TreeMap;
  6. //creating a class called "SimpleWordCounter"
  7. public class SimpleWordCounter {
  8. //creating a constructor for the object
  9. public static void main(String[] args) {
  10. //try to run the following:
  11. try {
  12. //creating an object from the class "File", named "f"
  13. File f = new File("ciaFactBook2008.txt");
  14. //intializing the Scanner
  15. Scanner sc;
  16. // assiging the value of the scanner object to new Scanner variable
  17. sc = new Scanner(f);
  18. // sc.useDelimiter("[^a-zA-Z']+");
  19. //creating a "Map" class that takes in 2 data types from the class map and "TreeMap for the object "wordCount"
  20. Map<String, Integer> wordCount = new TreeMap<String, Integer>();
  21. // creates a while loop checking for user input
  22. while(sc.hasNext()) {
  23. String word = sc.next();
  24. //if/else is nested in the while loop
  25. //creates an if/else loop for the object "wordCount"
  26. //if wordCount does not contain the word
  27. if(!wordCount.containsKey(word))
  28. //since it doesnt. pair the value 1 with the word and add to the map
  29. wordCount.put(word, 1);
  30. //if the "wordCount' does contain the word, increase the value of the word in the map by 1
  31. else
  32. wordCount.put(word, wordCount.get(word) + 1);
  33. }
  34. // show results
  35. //for each word in the "wordCount" insert a space in between the key and the value (the word and how many times the word occurs)
  36. for(String word : wordCount.keySet())
  37. System.out.println(word + " " + wordCount.get(word));
  38. //prints how many word there are
  39. System.out.println(wordCount.size());
  40. }
  41. //if the try fails because of an IOException, print error message
  42. catch(IOException e) {
  43. System.out.println("Unable to read from file.");
  44. }
  45. }
  46. }