Reading Input

Scanner can read tokens and lines from standard input. A token is a piece of input separated by spaces or line breaks, so 3 120 40 holds three tokens. Scanner is convenient for beginner programs because methods such as nextInt convert input as they read it.

import java.util.Scanner; makes the Scanner class available to your program, and new Scanner(System.in) creates one connected to standard input. You will learn what new does when you reach classes and objects.

Token methods leave the line-ending character behind. After nextInt, the extra nextLine consumes that remainder before the program reads a full name.

Read a number, then a line

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int guests = input.nextInt();
        input.nextLine();
        String venue = input.nextLine();
        System.out.println("Venue: " + venue);
        System.out.println("Guests: " + guests);
    }
}

Input:

120
River Hall

Output:

Venue: River Hall
Guests: 120

The input contains a count on one line and a venue with a space on the next. nextLine preserves the space inside the venue.

If you call nextLine immediately after nextInt without consuming the remainder, you get the rest of the number's line, which is an empty string, instead of the next real line.

Other token readers

Scanner has a reader for each common type. next reads one token as a String, nextDouble reads a decimal number, and nextLong reads a whole number too large for an int:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String city = input.next();
        double fare = input.nextDouble();
        long riders = input.nextLong();
        System.out.println("City: " + city);
        System.out.println("Fare: " + fare);
        System.out.println("Riders: " + riders);
    }
}

Input:

Lima 2.5 3000000000

Output:

City: Lima
Fare: 2.5
Riders: 3000000000

All three values sit on one line. Each reader takes the next token, skipping the spaces between them.

Read a release year and then a full movie title. Consume the leftover newline first.