Java Scanner — How to Take User Input

3 minute read

So far, all values in our programs have been hardcoded. Real programs need to accept input from users. Java’s Scanner class makes this easy.


Importing Scanner

Scanner lives in the java.util package:

import java.util.Scanner;

Creating a Scanner

Scanner scanner = new Scanner(System.in);

System.in represents the keyboard (standard input).


Reading Different Types

Reading a String (one word)

System.out.print("Enter your name: ");
String name = scanner.next();  // reads one word
System.out.println("Hello, " + name);
Enter your name: Alice
Hello, Alice

Reading a Full Line

System.out.print("Enter your full name: ");
String fullName = scanner.nextLine();  // reads entire line
System.out.println("Hello, " + fullName);
Enter your full name: Alice Johnson
Hello, Alice Johnson

Reading Numbers

System.out.print("Enter your age: ");
int age = scanner.nextInt();

System.out.print("Enter your GPA: ");
double gpa = scanner.nextDouble();

System.out.println("Age: " + age + ", GPA: " + gpa);

All Scanner Methods

Method Reads
next() One word (until whitespace)
nextLine() Entire line (until Enter)
nextInt() An int
nextLong() A long
nextDouble() A double
nextFloat() A float
nextBoolean() true or false
nextByte() A byte
nextShort() A short

The nextLine() Trap

This is the most common pitfall with Scanner:

System.out.print("Enter age: ");
int age = scanner.nextInt();

System.out.print("Enter name: ");
String name = scanner.nextLine();  // ⚠️ SKIPPED!

System.out.println("Age: " + age + ", Name: " + name);
Enter age: 25
Enter name: Age: 25, Name:

Why? nextInt() reads 25 but leaves the newline character (\n) in the buffer. nextLine() then reads that leftover newline and returns an empty string.

The Fix

Add a dummy nextLine() after nextInt() (or any nextXxx()):

System.out.print("Enter age: ");
int age = scanner.nextInt();
scanner.nextLine();  // consume the leftover newline

System.out.print("Enter name: ");
String name = scanner.nextLine();  // now works correctly

System.out.println("Age: " + age + ", Name: " + name);

Checking Before Reading — hasNextXxx()

You can check if valid input is available:

System.out.print("Enter a number: ");
if (scanner.hasNextInt()) {
    int num = scanner.nextInt();
    System.out.println("You entered: " + num);
} else {
    System.out.println("That's not a valid number!");
    scanner.next();  // discard invalid input
}

Reading Input in a Loop

Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers (type 'quit' to stop):");

while (scanner.hasNextInt()) {
    int num = scanner.nextInt();
    System.out.println("Got: " + num);
}

System.out.println("Done!");

Complete Example: Simple Calculator

import java.util.Scanner;

public class SimpleCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter first number: ");
        double a = scanner.nextDouble();

        System.out.print("Enter operator (+, -, *, /): ");
        String op = scanner.next();

        System.out.print("Enter second number: ");
        double b = scanner.nextDouble();

        double result = switch (op) {
            case "+" -> a + b;
            case "-" -> a - b;
            case "*" -> a * b;
            case "/" -> b != 0 ? a / b : Double.NaN;
            default -> {
                System.out.println("Unknown operator");
                yield 0;
            }
        };

        System.out.printf("%.2f %s %.2f = %.2f%n", a, op, b, result);
        scanner.close();
    }
}

Closing the Scanner

Always close the scanner when done:

scanner.close();

Or use try-with-resources (covered later):

try (Scanner scanner = new Scanner(System.in)) {
    // use scanner
}  // automatically closed

⚠️ After closing a Scanner on System.in, you cannot reopen it. Only close it when you’re completely done with all input.


Quick Exercises

  1. Write a program that asks for the user’s name and age, then prints: “Hello [name], you will be [age+1] next year!”
  2. Read 5 numbers in a loop and print their sum.
  3. Handle the nextLine() trap: read an int, then a full sentence.

Summary

Task Method
Read one word scanner.next()
Read full line scanner.nextLine()
Read integer scanner.nextInt()
Read decimal scanner.nextDouble()
Check before read scanner.hasNextInt()
Consume leftover newline scanner.nextLine() (dummy call)

What’s Next?

Next, let’s learn about comments — how to annotate your code so humans (including future you) can understand it: Comments in Java.

Updated: