// importing the java package that contains each class you would like to use import java.io.IOException; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; //creating a class called "SimpleWordCounter" public class SimpleWordCounter { //creating a constructor for the object public static void main(String[] args) { //try to run the following: try { //creating an object from the class "File", named "f" File f = new File("ciaFactBook2008.txt"); //intializing the Scanner Scanner sc; // assiging the value of the scanner object to new Scanner variable sc = new Scanner(f); // sc.useDelimiter("[^a-zA-Z']+"); //creating a "Map" class that takes in 2 data types from the class map and "TreeMap for the object "wordCount" Map wordCount = new TreeMap(); // creates a while loop checking for user input while(sc.hasNext()) { String word = sc.next(); //if/else is nested in the while loop //creates an if/else loop for the object "wordCount" //if wordCount does not contain the word if(!wordCount.containsKey(word)) //since it doesnt. pair the value 1 with the word and add to the map wordCount.put(word, 1); //if the "wordCount' does contain the word, increase the value of the word in the map by 1 else wordCount.put(word, wordCount.get(word) + 1); } // show results //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) for(String word : wordCount.keySet()) System.out.println(word + " " + wordCount.get(word)); //prints how many word there are System.out.println(wordCount.size()); } //if the try fails because of an IOException, print error message catch(IOException e) { System.out.println("Unable to read from file."); } } }