FrequencyTable.java


Below is the syntax highlighted version of FrequencyTable.java.


// Dependencies: ST.java (available on precepts page), StdIn, StdOut
public class FrequencyTable {
       // maintain counts of all words seen so far
       // the key is the word and the value is the count
       private ST<                 > st =                            ;
   
       // remark: we have not declared a constuctor! but Java lets every class 
       // have a no-argument constructor by default. It only runs the line of 
       // code above (instance variable initialization).
   
       // add 1 to the frequency of this word
       public void click(String word) {
           int count = count(word);
           st.put(word, count + 1);
       }
   
       // what is the frequency of this word?
       public int count(String word) {
           if (!st.          (      )) return 0;  // if word is not in ST
           else return     .     (      );        // get word's count
       }
   
       // print out all words and frequencies
       public void show() {
           // foreach loop. goes through all keys in alphabetical order
           for (String word : st) {
               // print out frequency and word, separated by a space
               StdOut.println(       (      ) + " " +       );
           }
       }
   
       // method used by client to count all words in StdIn
       public static void main(String[] args) {
   
           // build frequency table from words on standard input
           FrequencyTable freq = new FrequencyTable();
           while (!StdIn.isEmpty()) {
               String word = StdIn.readString();
               freq.       (word);
           }
   
           // print frequency table to standard output
           freq.show();
       }
}