FrequencyTable.java


Below is the syntax highlighted version of FrequencyTable.java.


/*************************************************************************
 *  Compilation:  javac FrequencyTable
 *  Dependencies: StdIn.java StdOut.java ST.java
 *  Execution:    java FrequencyTable < words.txt
 *  Data file:    http://introcs.cs.princeton.edu/java/44st/mobydick.txt
 *
 *  Read in a list of words from standard input and print out
 *  each word and the number of times it appears.
 *
 *  % java FrequencyTable < mobydick.txt
 *  4583 a
 *  2 aback
 *  2 abaft
 *  3 abandon
 *  7 abandoned
 *  1 abandonedly
 *  2 abandonment
 *  ...
 *
 *  % java FrequencyTable < mobydick.txt | sort -rn | more
 *  13967 the
 *  6415 of
 *  6247 and
 *  4583 a
 *  4508 to
 *  4037 in
 *  2911 that
 *  2481 his
 *  ...
 *
 *************************************************************************/

public class FrequencyTable {
    private ST<String, Integer> st = new ST<__________, ___________>();
    // add one to the count for the key
    public void click(String key) {
        if (!st.contains(key)) st.put(key, 1);
        else st.put(key, st.get(key) + 1);
    }

    // return the number of times the key appears
    public int count(String key) {
        if (!st.___________(______)) return 0; // if key is not in ST
        else return ______._________(______);  // get key's count
    }

    // print each key preceded by its count to standard output
    public void show() {
        for (String key : st) {   // iterate for each key in st
            StdOut.println(__________(key) + " " + _____________);
        }
    }

    public static void main(String[] args) {

        // build frequency table from words on standard input
        FrequencyTable freq = new FrequencyTable();
        while (!StdIn.isEmpty()) {
            String key = StdIn.readString();
            freq.__________(key); // call method to increment key's count
        }

        // print frequency table to standard output
        __________________();  

    }

}