KillianMills

WordFrequency.java

Oct 29th, 2014
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.96 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class WordFrequency{
  4.     public static void main(String [] args){
  5.         HashMap<Integer, Integer> recorder = new HashMap<>();
  6.        
  7.         System.out.println("Please enter word for the frequency recorder: ");
  8.        
  9.         while(!Console.endOfFile()){    //takes input until user is finished
  10.        
  11.             String userInput = Console.readToken();
  12.             int wordLength = userInput.length();
  13.            
  14.             if ( recorder.containsKey(wordLength) ){    //checks if key is recorded
  15.                 int counter = recorder.get(wordLength);
  16.                 counter++;
  17.                 recorder.put(wordLength, counter );
  18.             }
  19.            
  20.             else recorder.put(wordLength, 1);       //otherwise record key and set count to 1
  21.        
  22.             System.out.println("Please enter word for the frequency recorder: ");
  23.        
  24.         }
  25.        
  26.         // print out the word lengths and their frequency
  27.         Set<Integer> keys = recorder.keySet();
  28.         for(Integer wordLength : keys){
  29.             System.out.println("Word Length: " + wordLength + " Frequency: " + recorder.get(wordLength));
  30.         }
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment