MapHist.java


import java.io.*;
import java.util.*;

class WordHistogram {

    public static void main (String args[]) throws IOException 
    {
        Map histogram = new TreeMap();                            //(A)

        String allChars = getAllChars( args[0] );                 //(B)
        StringTokenizer st = new StringTokenizer( allChars );     //(C)
        while ( st.hasMoreTokens() ) {                            //(D)
            String word = st.nextToken();                         //(E)
            Integer count = (Integer) histogram.get( word );      //(F)
            histogram.put( word, ( count==null ? new Integer(1) 
                   : new Integer( count.intValue() + 1 ) ) );     //(G)
        }
        System.out.println( "Total number of DISTINCT words: " 
                                 + histogram.size() );            //(H)
        System.out.println( histogram );                          //(I)
    }

    static String getAllChars( String filename ) throws IOException {
        String str = "";
        int ch;
        Reader input = new FileReader( filename );
        while ( ( ch = input.read() ) != -1 )
            str += (char) ch;
            input.close();
            return str;
    }    
}


Results

C:\classes\ece538\work\kak05>javac MapHist.java
Note: MapHist.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

C:\classes\ece538\work\kak05>java WordHistogram InFile
Total number of DISTINCT words: 2
{cat=4, dog=5}


Maintained by John Loomis, updated Sun Jan 07 15:33:42 2007