////// WordCount.java ////// import java.io.*; class WordCount { private static boolean readInput(Cirbuf b) // read stdin throws IOException { int c; while ( ! b.isFull() ) // while b not full if ( (c = System.in.read()) != -1) b.put((char)c); // deposit into buffer else return(false); // input closed return(true); // buffer full } private static void wordCount(Cirbuf b) // count number of words { while ( ! b.isEmpty() ) // while buffer not empty { b.get(inc); switch( inc[0] ) // remove one character from buffer { case ' ' : case '\r': case '\t': case '\n': // word delimiters if ( word ) wcnt++; // word complete word = false; // partial word indicator false break; default: word = true; // partial word indicator true } } } public static void main(String[] args) throws IOException { Cirbuf bf = new Cirbuf(128); wcnt = 0; word = false; for (;;) if ( readInput(bf) ) // producer wordCount(bf); // consumer else { wordCount(bf); if ( word ) wcnt++; break; } System.out.println("total " + wcnt + " words"); } private static int wcnt = 0; // total word count private static boolean word = false; // partial word indicator private static char[] inc = new char[1]; }