import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;

public class WordCount {
    Hashtable ht;
    int count;

    public WordCount () {
	ht = new Hashtable ();
	count = 0;
    }

    public void processWord (String word) {
	count++;
	Integer i = (Integer) ht.get (word);
	if (i == null) {
	    ht.put (word, new Integer (1));
	} else {
	    Integer j = new Integer (i.intValue() + 1);
	    ht.put (word, j);
	}
    }

    public void processLine (String s) {
	StringTokenizer st = new StringTokenizer (s, " (),.\"\'`:[];?!=");
	while (st.hasMoreTokens()) {
	    String word = st.nextToken();
	    processWord (word.toLowerCase ());
	}
    }

    public String randomWord () {
	int x = randInt (0, count-1);
	Enumeration keys = ht.keys ();
	int total = 0;
	while (keys.hasMoreElements ()) {
	    Object key = keys.nextElement ();
            Integer value = (Integer) ht.get (key);
	    total += value.intValue ();
	    if (total > x) return (String) key;
	}
	// we should never get here
	return null;
    }

    // randInt: returns a random number between low and high,
    // including both endpoints
    public static int randInt (int low, int high) {
        while (true) {
            int x = (int)(Math.random() * (high-low+1) + low);
            if (x >= low && x <= high) return x;
        } 
    }

}


