Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Keyboard input

A program gets more interesting when it responds to the user. In Java 25 you can read a line from the keyboard with a single IO.readln() call, while older code uses the Scanner class for that.

IO.readln

IO.readln() prints a prompt, waits for the user to type text and press Enter, and returns what was typed as a String:

void main() {
    String name = IO.readln("What is your name? ");
    IO.println("Hello, " + name + "!");
}

Output (the user typed Anna):

What is your name? Anna
Hello, Anna!

The program stops at readln() and waits for input. Without an argument, IO.readln() reads a line without a prompt.

Reading numbers

readln() always returns a string, even if the user typed digits. To calculate with them, turn the string into a number with Integer.parseInt():

void main() {
    int year = Integer.parseInt(IO.readln("Year of birth: "));
    IO.println("In 2030 you will be " + (2030 - year));
}

Output (the user typed 1995):

Year of birth: 1995
In 2030 you will be 35

For fractional numbers use Double.parseDouble(). If the user types something that is not a number, parseInt() throws a NumberFormatException — the lesson on type conversion shows an example.

Several values

Each readln() call reads one line, so several values are simply read one after another:

void main() {
    int a = Integer.parseInt(IO.readln("First number: "));
    int b = Integer.parseInt(IO.readln("Second number: "));
    IO.println("Sum: " + (a + b));
}

Output (the user typed 7 and 5):

First number: 7
Second number: 5
Sum: 12

Scanner

Before Java 25, input was read with the Scanner class. You create it once, passing System.in — the keyboard input stream. The nextLine() method reads a line, nextInt() reads a whole number:

void main() {
    Scanner scanner = new Scanner(System.in);
    IO.print("How many cups of coffee? ");
    int cups = scanner.nextInt();
    IO.println("To pay: $" + cups * 3);
}

Output (the user typed 2):

How many cups of coffee? 2
To pay: $6

In the short program form Scanner is available right away. In the classic form you need the line import java.util.Scanner; at the top of the file.

Common mistake

nextInt() reads only the number, and the line break after it stays in the input. The next nextLine() picks up that leftover and immediately returns an empty string:

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

Output (the user typed 30 and pressed Enter):

Age: 30
Name: [], 30

The program did not even let the user type a name. Call an extra scanner.nextLine() after nextInt(), or read everything with IO.readln() and Integer.parseInt() — that way the problem does not exist.

Thanks for reading!

Donate to the site — we work hard for you.