Java Arena
Step 1 of 4

Reading a line with Scanner

So far the programs printed the same thing every time. Most programs also take input: something the user types. In Java, a Scanner reads it. Using one takes three pieces:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Write a message:");
        String message = scanner.nextLine();
        System.out.println(message);
    }
}
Input
Hello there
Output
Write a message:
Hello there
  • import java.util.Scanner; at the very top tells the compiler where the Scanner comes from. Scanner is part of Java's standard library, in the package java.util, and a program has to import it before using it.
  • Scanner scanner = new Scanner(System.in); creates a Scanner called scanner that reads from System.in, the program's input. One Scanner is enough for the whole program.
  • String message = scanner.nextLine(); waits until the user has typed a line and pressed Enter, then keeps that line in message. The next step explains what String message means.

Input on this site

When you run a program in a terminal, you type the input while it runs, and your typing appears on the screen between the program's lines. The checks here give the program all of its input at the start instead, like a pre-typed answer sheet, so the expected output only contains what the program itself prints. That's why Hello there appears once in the output above, not twice.

Your task

Challenge 1 of 3

Fill in the two blanks: the class to import, and the Scanner method that reads a whole line. The program then prints back whatever line it reads.

Challenge 2

Read one line, then print You said: followed by the line twice, each on its own line. For the input Good morning the program prints:

You said:
Good morning
Good morning

Challenge 3

Write the whole program: read one line and print it three times, between two lines of five equals signs. For the input Java it prints:

=====
Java
Java
Java
=====