Java User Input

Read text and numbers typed by the user with the Scanner class, and avoid the classic nextLine() trap.

Lesson 12 of 127Beginner18 min read

Programs become much more interesting when they respond to the person using them. A calculator needs numbers, a quiz needs answers and a greeting needs a name. In a console program, that information comes from the keyboard.

Java reads keyboard input with the Scanner class from the java.util package. You create one Scanner connected to System.in, the standard input stream, then call methods such as nextLine() for text and nextInt() for whole numbers. Each call waits until the user types something and presses Enter.

In this lesson you'll read text and numbers, learn why mixing nextInt() and nextLine() can skip input, check that the user really typed a number, and format your output neatly with printf. These are the building blocks of every interactive console program.

Creating a Scanner

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("What's your name? ");
        String name = input.nextLine();
        System.out.println("Hello, " + name + "!");
    }
}
  • The import line at the top makes the Scanner class available. It goes above the class.
  • new Scanner(System.in) creates a Scanner that reads from the keyboard. Create one and reuse it.
  • Using print instead of println for the question keeps the cursor on the same line, which looks natural.

Reading different types

MethodReadsExample input
nextLine()A whole line of text, including spacesAda Lovelace
next()One word, up to the next spaceAda
nextInt()A whole number42
nextDouble()A decimal number3.75
nextBoolean()true or falsetrue

The number methods convert the text for you, so int age = input.nextInt(); gives you a real int that you can do maths with. If the user types something that isn't a number, such as ten, the program stops with an InputMismatchException.

The nextLine() trap

nextInt() reads the number but leaves the Enter key in the input. A nextLine() straight afterwards reads that leftover Enter and returns an empty string, so it looks as if Java skipped your question:

Java
int age = input.nextInt();
input.nextLine();               // throw away the leftover Enter
String city = input.nextLine(); // now this waits properly

The fix is to call nextLine() once to consume the rest of the line after reading a number. Another common approach is to read everything with nextLine() and convert it yourself with Integer.parseInt(...), which avoids the trap completely.

Checking input before reading it

hasNextInt() looks at the next input without reading it and returns true only if it's a valid whole number. Combined with a loop, it lets you keep asking until the input is valid:

Java
while (!input.hasNextInt()) {
    System.out.print("Please enter a number: ");
    input.next();   // discard the bad word
}
int number = input.nextInt();

There are matching methods such as hasNextDouble() and hasNextLine(). Validating input this way keeps your program from crashing when someone makes a typo.

Reading several values on one line

A Scanner splits input into tokens separated by spaces, tabs or new lines. Methods such as nextInt() don't care whether the values were typed on one line or several. If the user types 3 4 and presses Enter, two calls to nextInt() read 3 and then 4:

Java
System.out.print("Width and height: ");
int width = input.nextInt();
int height = input.nextInt();
System.out.println("Area: " + width * height);

When you need the whole line, for example to check how many values were typed, read it with nextLine() and split it yourself: String[] parts = input.nextLine().trim().split("\\s+");. Each piece is a String, so convert it with Integer.parseInt(parts[0]).

Decimal numbers and the locale

nextDouble() follows the computer's locale, its language and region settings. On a computer set to German or French, it expects a decimal comma, 3,5, and treats 3.5 as invalid input. If your program should always accept a decimal point, set the locale once after creating the Scanner:

Java
Scanner input = new Scanner(System.in).useLocale(java.util.Locale.UK);

Reading the text with nextLine() and converting it with Double.parseDouble() also always uses a decimal point, because parseDouble ignores the locale.

Java User Input Syntax

Scanner and printf

import java.util.Scanner;

Scanner input = new Scanner(System.in);
String line = input.nextLine();
int n = input.nextInt();
double d = input.nextDouble();
input.nextLine();                 // clear the rest of the line

System.out.printf("%s is %d%n", name, age);

Java User Input Summary

  • import java.util.Scanner; then Scanner input = new Scanner(System.in);.
  • nextLine() reads a line, nextInt() and nextDouble() read numbers.
  • After nextInt(), call nextLine() once before reading more text.
  • hasNextInt() checks input before reading it, so you can validate.
  • printf with %s, %d, %.2f and %n formats output neatly.

Java User Input Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A personal greeting

Here the user typed Rosa Diaz, then 16.

Java
import java.util.Scanner;

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

        System.out.print("Full name: ");
        String name = input.nextLine();

        System.out.print("Age: ");
        int age = input.nextInt();

        System.out.println("Hi " + name + "!");
        System.out.println("In ten years you'll be " + (age + 10) + ".");
    }
}
Output
Full name: Rosa Diaz
Age: 16
Hi Rosa Diaz!
In ten years you'll be 26.
Line-by-line explanation
  1. Line 1Import Scanner before the class.
  2. Line 8nextLine() keeps the space between first and last name.
  3. Line 11nextInt() converts the input to an int.
  4. Line 14Brackets make the addition happen before joining with text.
Example 2

A bill splitter with printf

Here the user typed 84.60 and 3.

Java
import java.util.Scanner;

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

        System.out.print("Total bill: ");
        double total = input.nextDouble();
        System.out.print("Number of people: ");
        int people = input.nextInt();

        double share = total / people;
        System.out.printf("Each person pays £%.2f%n", share);
        System.out.printf("%d people, £%.2f in total%n", people, total);
    }
}
Output
Total bill: 84.60
Number of people: 3
Each person pays £28.20
3 people, £84.60 in total
Line-by-line explanation
  1. Line 8nextDouble() reads a decimal number.
  2. Line 13%.2f shows exactly two decimal places, and %n ends the line.
  3. Line 14Several values fill the placeholders in order.
Example 3

Asking again until the input is valid

Here the user typed ten, then -4, then 7.

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int tickets = 0;

        while (tickets < 1) {
            System.out.print("How many tickets? ");
            if (input.hasNextInt()) {
                tickets = input.nextInt();
                if (tickets < 1) System.out.println("At least one, please.");
            } else {
                System.out.println("That isn't a number.");
                input.next();
            }
        }
        System.out.println("Booking " + tickets + " tickets.");
    }
}
Output
How many tickets? ten
That isn't a number.
How many tickets? -4
At least one, please.
How many tickets? 7
Booking 7 tickets.
Line-by-line explanation
  1. Line 8Keep asking until a valid number of tickets has been read.
  2. Line 10hasNextInt() checks the input without consuming it.
  3. Line 15next() throws away the invalid word so the loop can ask again.

Common Java User Input Mistakes

Forgetting the import

Don't
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);   // cannot find symbol
    }
}
Do
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
    }
}

nextLine() straight after nextInt()

Don't
int age = input.nextInt();
String city = input.nextLine();   // returns "" immediately
Do
int age = input.nextInt();
input.nextLine();
String city = input.nextLine();

Reading a full name with next()

Don't
String name = input.next();       // "Rosa Diaz" gives only "Rosa"
Do
String name = input.nextLine();

Java User Input in Real Projects

Input in real programs

Command-line tools such as installers and setup wizards ask questions exactly this way, and programming contest platforms feed test data into your program through standard input. In larger applications, input usually arrives from forms, files or web requests instead, but the same ideas apply: read it, convert it to the right type and validate it before you trust it.

Java User Input FAQ

Should I close the Scanner in Java?

A Scanner on System.in also closes System.in when you close it, and the program can't read from the keyboard again afterwards. In small programs, create one Scanner and either close it once at the very end of main or leave it open. Never close it in a method that runs more than once. Scanners reading files should always be closed, ideally with try-with-resources.

What is the difference between next() and nextLine()?

next() reads one token, a word up to the next space, and leaves the rest of the line for later calls. nextLine() reads everything up to the end of the line, spaces included, and consumes the Enter. Use nextLine() for names, addresses and sentences.

Why do I get an InputMismatchException?

The next token doesn't match the type you asked for, for example nextInt() when the user typed ten or 4.5. Check first with hasNextInt() or hasNextDouble(), or read a line and convert it inside a try/catch for NumberFormatException.

How do I read a single character with Scanner?

Scanner has no nextChar() method. Read a token and take its first character: char answer = input.next().charAt(0);. Convert it with Character.toLowerCase(answer) if you want Y and y to count as the same answer.

Is BufferedReader better than Scanner?

BufferedReader is faster for reading large amounts of text, which matters in competitive programming or when processing big files. It only reads lines, so you convert numbers yourself. For interactive console programs Scanner is simpler and fast enough.

Java User Input Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the line that creates a Scanner reading from the keyboard.

Scanner input = new (System.);
Multiple choiceeasy

Which method reads a whole line of text, including spaces?

Predict the outputmedium

The user types Sam Lee. What does this print?

String first = input.next();
System.out.println("Hi " + first);
Predict the outputmedium

What does this print?

System.out.printf("%.1f%n", 7.0 / 2);
Multiple choicehard

Why might nextLine() return an empty string right after nextInt()?

Java User Input Quiz

5 questions to check what you learned.

  1. Which package contains the Scanner class?

    • java.io
    • java.lang
    • java.input
    • java.util
  2. What does nextInt() return?

    • A String
    • A double
    • A char
    • An int
  3. What happens if the user types abc when nextInt() is waiting?

    • It throws an InputMismatchException
    • It returns 0
    • It returns -1
    • It waits forever
  4. What does %d mean in a printf template?

    • A decimal number with two places
    • A date
    • A whole number
    • A double quote
  5. What does hasNextInt() do?

    • Reads the next int
    • Checks whether the next input is a valid int, without reading it
    • Skips the next int
    • Converts the input to an int