Codiqo

Learn Java · lesson 8 of 61 · about 8 minutes

Reading Input with Scanner

Let a customer book at the desk: read their name and how many seats they want with Scanner, and dodge the leftover-newline trap.

What you'll learn

  • Create a Scanner
  • Read with nextInt, next and nextLine
  • Avoid the leftover-newline trap

Scanner

To read what someone types, Java uses a Scanner. It lives in a library package, so the file starts with import java.util.Scanner;, and main makes one: Scanner in = new Scanner(System.in);.

  • in.nextLine() reads the whole line, spaces included
  • in.next() reads one word
  • in.nextInt() reads a whole number
  • in.nextDouble() reads a decimal

A customer books

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String customer = in.nextLine();
        int tickets = in.nextInt();
        System.out.println(customer + " books " + tickets + " tickets");
    }
}

Output

Ada Lovelace books 3 tickets

The leftover newline

When someone types 3 and presses Enter, nextInt() takes the 3 but leaves the Enter behind. A nextLine() straight after reads up to that Enter and gets an empty String.

Read the lines first, or read the number as a line and turn it into an int: Integer.parseInt(in.nextLine()).

The trap: the name comes out empty

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int tickets = in.nextInt();
        String customer = in.nextLine();
        System.out.println("[" + customer + "] books " + tickets);
    }
}

Output

[] books 3

Tip

What the user types doesn't appear in the output here; only what the program prints does.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.