Java Arena
Step 1 of 9

Reading until the input ends

This module is about reading data from files. A program reads a file one line at a time, much as it reads what a user types, so it starts at the keyboard.

Module 19 read input in a while (true) loop that stops at a signal, such as an empty line: read a line, break if it's the signal, and only then use it. This step adds two more ways to know when to stop.

Until the input ends

A Scanner's hasNextLine() tells whether there's another line to read. It's true while there is one, and false once the input has ended, so a loop can read every line without waiting for a signal:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int count = 0;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            count++;
            System.out.println(count + ": " + line);
        }
        System.out.println("Lines: " + count);
    }
}
Input
red
green
blue
Output
1: red
2: green
3: blue
Lines: 3
  • hasNextLine() only looks. nextLine() then reads the line, so the next round sees the line after it.
  • An empty line is a line too: hasNextLine() is true for it, and nextLine() gives "".
  • In the checks on this site, the input ends after its last line. A person at a keyboard has no natural end, which is why keyboard programs usually wait for a stop signal instead. (In a terminal, Ctrl+D ends the input, or Ctrl+Z and then Enter on Windows.)

A file does have an end, and this loop is exactly how the next steps read one.

A stop word in any capitals

A stop word typed by a person may come as end, End or END. equalsIgnoreCase from module 16 accepts all of them:

String line = scanner.nextLine();
if (line.equalsIgnoreCase("end")) {
    break;
}

Your task

Challenge 1 of 3

The program reads a letter until its input ends, and prints how many lines it has and how many of them are empty (the gaps between paragraphs). Fill in the blanks. For the input shown below, it prints:

Lines: 5
Empty lines: 2

Challenge 2

Read words until the stop word end, which may be typed in any capitals, such as End or END. Print each word in capital letters with ! after it, and at the end the number of words, not counting the stop word. For the input hello, world, End, the program prints:

HELLO!
WORLD!
Words: 2

Challenge 3

A traffic counter types a line for each vehicle that passes: car, bike or bus. Read the lines until the input ends, with hasNextLine(), and print how many vehicles of each kind passed. For the input shown below, the program prints:

Cars: 3
Bikes: 2
Buses: 1