The Java Program: WordCount.java

  1 // WordCount.java -- simple program counting lines, words, and chars
  2 
  3 class WordCount {
  4 
  5    static final String text = "Now is the time\n" +
  6       "for all good men\n" +
  7       "to come to the aid\n" +
  8       "of their country\n" +
  9       "and pay their due taxes\n";
 10 
 11    static final int len = text.length();
 12 
 13    static public void main (String args[]) {
 14       boolean inWord = false;
 15       int numChars = 0;
 16       int numWords = 0;
 17       int numLines = 0;
 18 
 19       for (int i = 0; i<len; i++) {
 20          final char c = text.charAt(i);
 21          numChars++;
 22          switch (c) {
 23          case '\n':
 24             numLines++;
 25             // FALLSTHROUGH
 26          case '\t':
 27          case ' ':
 28             if (inWord) {
 29                numWords++;
 30                inWord = false;
 31             }
 32             break;
 33          default:
 34             inWord = true;
 35          }
 36       }
 37 
 38       System.out.println ("\t" + numLines +
 39                           "\t" + numWords +
 40                           "\t" + numChars);
 41    }
 42 }