Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to read user input

Short answer

In Java 25, IO.readln() reads a line from the keyboard. You can pass a prompt — it is printed before the input:

void main() {
    String name = IO.readln("Your name: ");
    IO.println("Hello, " + name + "!");
}

Output:

Your name: Hello, Anna!

Here the user typed Anna. In a terminal the typed text appears after the prompt; the output above shows only what the program printed.

A number

readln() returns a string — get a number from it with Integer.parseInt():

void main() {
    int year = Integer.parseInt(IO.readln("Birth year: ").strip());
    IO.println("Age in 2026: " + (2026 - year));
}

Output:

Birth year: Age in 2026: 36

Repeating until the input is valid

Ask again until the input is a number:

void main() {
    while (true) {
        String text = IO.readln("Quantity: ");
        try {
            int quantity = Integer.parseInt(text.strip());
            IO.println("OK: " + quantity);
            break;
        } catch (NumberFormatException e) {
            IO.println("Please enter a whole number.");
        }
    }
}

Output:

Quantity: Please enter a whole number.
Quantity: OK: 10

The user first typed ten, then 10.

Scanner

Before Java 25 people use Scanner. It can read numbers and words separately:

void main() {
    var scanner = new Scanner(System.in);
    int a = scanner.nextInt();
    int b = scanner.nextInt();
 
    IO.println(a + " * " + b + " = " + a * b);
}

Output:

3 * 4 = 12

Common mistake

Mixing nextInt() and nextLine() on a Scanner. nextInt() leaves the line break in the buffer, and the next nextLine() immediately returns an empty string:

void main() {
    var scanner = new Scanner(System.in);
    int age = scanner.nextInt();
    String name = scanner.nextLine();
 
    IO.println("age=" + age + ", name=[" + name + "]");
}

Output:

age=30, name=[]

Read whole lines with nextLine() or IO.readln() and parse numbers with parseInt().

Functions used in this recipe

  • IO.readln() — Prints a prompt and reads a line typed by the user.
  • Scanner — Reads input piece by piece: whole lines (nextLine) or separate words and numbers.
  • Integer.parseInt() — Converts a string containing an integer to an int.

Thanks for reading!

Donate to the site — we work hard for you.