Reading Different Types

Scanner Methods

MethodReads
nextLine()a whole line (including spaces)
next()one word (up to whitespace)
nextInt(), nextLong()whole numbers
nextDouble()decimal numbers
nextBoolean()true / false
hasNext(), hasNextInt()checks if more input (of that type) is available

Mixed Input

Example

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner("Laptop 2 54999.99 true\n10 20 30 40\n");
        String product = sc.next();
        int qty = sc.nextInt();
        double price = sc.nextDouble();
        boolean express = sc.nextBoolean();
        System.out.println(product + " x" + qty + " = " + qty * price + ", express: " + express);

        int sum = 0;
        while (sc.hasNextInt()) {
            sum += sc.nextInt();
        }
        System.out.println("Sum of numbers: " + sum);
    }
}

Output

Laptop x2 = 109999.98, express: true
Sum of numbers: 100

The nextInt + nextLine Trap

Example

nextInt() reads the number but leaves the newline. The next nextLine() then returns an empty string. Fix it with an extra nextLine().

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner("25\nAnjali Rao\n");
        int age = sc.nextInt();
        String rest = sc.nextLine();      // reads the leftover "" (end of line 1)
        String name = sc.nextLine();      // now reads the real name
        System.out.println("age=" + age + ", leftover=[" + rest + "], name=" + name);
    }
}

Output

age=25, leftover=[], name=Anjali Rao

Tip: Another common fix: read every line with nextLine() and convert with Integer.parseInt(...).