WordCount.java


Below is the syntax highlighted version of WordCount.java from §1.5 Input and Output.


/******************************************************************************
 *  Compilation:  javac WordCount.java
 *  Execution:    java WordCount
 *         [ input required from standard input                        ]
 *         [ use Ctrl-d (OS X or Dr. Java) or Ctrl-z (Windows) for EOF ]
 *
 *  Dependencies: StdIn.java StdOut.java
 *
 *  Read in a sequence of strings from standard input and print out
 *  the number of strings read in.
 *
 *  % java WordCount
 *  it was the best of times
 *  it was the worst of times
 *  number of words  = 12
 *  Ctrl-d
 *
 *  % java WordCount < tale.txt
 *  number of words  = 139043
 *
 ******************************************************************************/

public class WordCount {
    public static void main(String[] args) {

        int count = 0;
        while (!StdIn.isEmpty()) {
            String word = StdIn.readString();
            count++;
        }

        // output
        StdOut.println("number of words  = " + count);
    }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:14:17 EDT 2022.