import java.util.*; import java.io.*; public class CountWords // class to count the number of unique words in a file using a map class (HashMap) { public static void main(String[] args) { String filename; HashMap map=new HashMap<>(); // our HashMap will store the word as the key and the number of String temp; // occurrences as the value, this will have to be an Integer char lastChar; // used to prune off the last character if it is a punctuation Integer i; // temp Integer variable used when increment the count by 1 try { Scanner in1=new Scanner(System.in); // keyboard input to get the filename System.out.print("Enter the file name: "); filename=in1.next(); Scanner in2=new Scanner(new File(filename)); // file input while(in2.hasNext()) // read the file one String at a time { temp=in2.next().toLowerCase(); // get the next String, lower case it lastChar=temp.charAt(temp.length()-1); // get the last character if(lastChar=='.'||lastChar==',') // if punctuation then prune it off of temp temp=temp.substring(0,temp.length()-1); if(map.containsKey(temp)) // is temp already in the map? { i=map.get(temp); // if so, get ahold of this entry's value (an Integer) i=new Integer(i.intValue()+1); // and create a new Integer that is 1 greater map.put(temp,i); // if temp is already in the map, this replaces it, thus } // replacing temp,i with temp,i+1 else { map.put(temp,new Integer(1)); // otherwise temp is new, insert it with a count of 1 } } System.out.println(map); // output the map when done } catch(IOException e) // needed if the file does not exist or is { // corrupted System.out.println(e); } } }