bhylu.com

Advertisements

Java Read and Validate Console Input

Console input arrives as text. Parse it at a clear boundary and decide what malformed or out-of-range values should mean before using them in a calculation.

Understand the idea

Scanner can read tokens or complete lines. Mixing nextInt with nextLine often surprises beginners because the line separator after the numeric token is still waiting to be consumed. Reading full lines and then parsing each required value makes the boundary explicit. This standalone program owns its console session; a reusable library should not close a caller-owned shared input stream.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

Provide these separate input lines when prompted:

4
5

A worked example

Java 21+ · Main.java

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            int first = Integer.parseInt(input.nextLine().strip());
            int second = Integer.parseInt(input.nextLine().strip());
            if (first < 0 || second < 0) throw new IllegalArgumentException("counts must be non-negative");
            System.out.println(Math.addExact(first, second));
        }
    }
}

Expected output

9

Supply two input lines containing 4 and 5. Each line is stripped, parsed and validated before the addition. The program expects exactly those required lines; a production command-line interface would also explain missing input and provide helpful recovery messages. The expected result is independent of terminal prompt styling.

Check the official Java documentation for detailed contracts and supported options.