// code to demonstrate reading until end-of-file in Java // NOTE: this is an example of over-documentation! This file has more // documentation than appropriate for regular code. Never write a // comment that another skilled programmer would find obvious! // Sample usage: // java CountLines.java < CountLines.java // This runs the program at the command prompt, using itself as input. // You could also do something like // // javac CountLines.java // java CountLines // this is a line of text // a second line of text // [eof mark] // // where "[eof mark]" would be control-D (hold down the control key and // press D) on Unix and in IntelliJ or control-Z in the Windows command prompt. // In both cases, the output would be "Line count: 2". import java.util.Scanner; public class CountLines { public static void main(String[] args) { int count = 0; // see comments for elements of an end-of-file loop in Java // initializing the scanner Scanner input = new Scanner(System.in); // while scanner has more data to process while ( input.hasNext() ) { // read the data String text = input.nextLine(); // process it; (in this case, simply count the line, but one // could store some or all of the text in some container or // count lines with particular substrings, etc.) count += 1; } // trivial output to show the code did something: System.out.println("Line count: " + count); } }