1. java-hell.de
  2. Topics
  3. User Input
Topic 10 of 11

Learn Java User Input – Read Input

So far your program only talks. Now it listens too: with IO.readln() you read input, turn it into numbers and build your first interactive programs.

The exercises

What you'll learn in this topic

  1. Greeting the user
  2. Adding two numbers
Exercise 1 of 2

Greeting the user

So far your programs have only printed stuff. Now they read input too.

With IO.readln() your program waits until the user types something and hits Enter. The typed text comes back as a String.

String name = IO.readln("Name: ");
IO.println("Hello, " + name);

Below there's an input field. Whatever is in it gets passed to the program as input — one line per answer. Try it out and type in your name!

Test environment

Normally the user types live in the terminal. Here we simulate that with the text field below — each line is the answer to one question.

Starter code
void main() {
    String name = IO.readln("Name: ");
    IO.println("Hello, " + ???);
}
Background
IO.readln vs. Scanner

In older Java code you'll often see the Scanner class for input:

Scanner sc = new Scanner(System.in);
String name = sc.nextLine();

IO.readln() from Java 25 is the shorter successor — it does the same job, but without the boilerplate and without an import.

The prompt string ("Name: ") is printed before the input, without a line break.

Exercise 2 of 2

Adding two numbers

IO.readln always gives you a String. For numbers you still have to convert the string:

int number = Integer.parseInt(IO.readln("Number: "));

Read in two numbers and print their sum.

With the input 7 and 5, the last number printed should be 12.

Starter code
void main() {
    int a = Integer.parseInt(IO.readln("First number: "));
    // Read the second number and print the sum
}
Background
What happens with bad input?

If the user types something that isn't a number (e.g. "abc"), Integer.parseInt throws a NumberFormatException. In a real program you'd catch that with try/catch — just like you did in the "Exceptions" block.

Enough reading. Your turn.

In the tutorial you write the code yourself, hit Run and instantly see whether your program works. No JDK, no IDE, no bullshit.

Practice User Input in your browser