User Input with Scanner
Reviewed & published by Brayan K
Until now your programs only printed hard-coded values. Real programs react to people. The Scanner class reads what the user types at the keyboard — turning your code into an interactive conversation.
Part of the free Java course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- Importing and creating a Scanner
- Reading text with nextLine() and next()
- Reading numbers with nextInt() and nextDouble()
- The infamous 'skipped nextLine()' newline bug
- Validating input with hasNextInt()
- Closing the Scanner cleanly
1️⃣ Three Steps to Read Input
Reading keyboard input always follows the same recipe:
- Import the class: import java.util.Scanner; at the very top.
- Create a Scanner wired to the keyboard: Scanner scanner = new Scanner(System.in);
- Read with a method like nextLine(), nextInt(), or nextDouble().
💡 What is System.in? Just as System.out is the output stream (the screen), System.in is the input stream (the keyboard). A Scanner wraps that raw stream and gives you friendly methods to pull out words, lines, and numbers.
Tip: use System.out.print (no ln) for prompts so the cursor stays on the same line as the user's typing.
import java.util.Scanner; // Scanner lives in java.util, so import it
public class Main {
public static void main(String[] args) {
// 1. Create a Scanner that reads from the keyboard (System.in)
Scanner scanner = new Scanner(System.in);
// 2. Prompt, then read a line of text
System.out.print("What's your name? ");
String name = scanner.nextLine();
// 3. Use what the user typed
System.out.println("Nice to meet you, " + name + "!");
// 4. Always close the Scanner when you're done
scanner.close();
}
}2️⃣ The Reading Methods
The Scanner has a method for each kind of value. Pick the one that matches the data you expect:
| Method | Reads | Returns |
|---|---|---|
| nextLine() | The whole rest of the line | String |
| next() | One word (token) | String |
| nextInt() | A whole number | int |
| nextDouble() | A decimal number | double |
| nextBoolean() | true / false | boolean |
| hasNextInt() | Peeks: is the next token an int? | boolean |
3️⃣ The #1 Scanner Gotcha: the Leftover Newline
Almost every beginner hits this bug. When you call nextInt() and the user types 30 and presses Enter, the Scanner reads 30 but leaves the invisible newline character (from Enter) sitting in the buffer.
The next nextLine() then immediately reads that leftover newline and returns an empty string — it looks like your prompt was skipped!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // reads an int
System.out.print("Enter your height in metres: ");
double height = scanner.nextDouble(); // reads a double
scanner.nextLine(); // consume the leftover newline (see Gotcha!)
System.out.print("Enter your city: ");
String city = scanner.nextLine(); // reads the rest of the line
int nextAge = age + 1;
System.out.println("---");
System.out.println("Next year you'll be " + nextAge);
System.out.printf("You are %.2f m tall.%n", height);
System.out.println("You live in " + city + ".");
scanner.close();
}
}4️⃣ Don't Trust the User — Validate
If you call nextInt() and the user types "banana", the program crashes with an InputMismatchException. Professional code never assumes the input is valid.
The hasNextInt() method peeks at the next token without consuming it, returning true only if it could be read as an int. Loop on it to keep asking until the input is good:
while (!scanner.hasNextInt()) {
System.out.print("Please enter a whole number: ");
scanner.next(); // discard the offending token
}
int n = scanner.nextInt();import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Defensive input: keep asking until we get a valid whole number.
System.out.print("How many tickets? ");
while (!scanner.hasNextInt()) { // is the next token an int?
System.out.print("Please enter a whole number: ");
scanner.next(); // throw away the bad token
}
int tickets = scanner.nextInt();
final double PRICE = 12.50;
double total = tickets * PRICE;
System.out.printf("%d tickets x $%.2f = $%.2f%n", tickets, PRICE, total);
scanner.close();
}
}import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// 🎯 YOUR TURN — replace each ___ using the hint beside it.
//
// A Scanner can read from a String instead of System.in. That is how you
// TEST input code: the same methods, without anyone typing.
String typed = "Ada\n34\n1.75\n";
Scanner in = new ___(typed); // 👉 replace ___ with Scanner
// 1) A whole line, spaces and all.
String name = in.___(); // 👉 replace ___ with nextLine
// 2) Just the number. Leaves the newline after it sitting there.
int age = in.___(); // 👉 replace ___ with nextInt
// 3) The decimal one.
double height = in.___(); // 👉 replace ___ with nextDouble
// 4) Swallow that leftover newline, or the next nextLine() reads "".
in.___(); // 👉 replace ___ with nextLine
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Anything left? " + in.hasNextLine());
in.close();
// 5) Ask BEFORE reading, and bad input never throws.
Scanner messy = new Scanner("twelve");
if (messy.___()) { // 👉 replace ___ with hasNextInt
System.out.println("Got a number");
} else {
System.out.println("That was not a number: " + messy.next());
}
messy.close();
}
}🧩 Reorder Challenge
Put these lines in the right order to ask for a name and print a greeting.
String name = scanner.nextLine();
Scanner scanner = new Scanner(System.in);
System.out.println("Hello, " + name + "!");
System.out.print("Name? ");
scanner.close();Scanner scanner = new Scanner(System.in);
System.out.print("Name? ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();Why: You must create the Scanner before using it. Print the prompt, then read the answer into name, then use name in the greeting. Closing the Scanner comes last, once you no longer need input.
🧠 Quick Recall
1. The user types Mary Jane and presses Enter. What does scanner.next() return?
"Mary". next() stops at the first space, reading only one token. nextLine() would return the whole "Mary Jane".
2. After int age = scanner.nextInt(); with the user typing 40 + Enter, what does the very next scanner.nextLine() return?
An empty string "" — it reads the leftover newline. That's the gotcha; add an extra nextLine() to flush it.
3. The user types abc when the code calls scanner.nextInt(). What happens?
An InputMismatchException is thrown and the program crashes — unless you guarded it with hasNextInt() first.
Common Beginner Mistakes
- ❌ Forgetting the import: no import java.util.Scanner; means "cannot find symbol Scanner".
- ❌ The skipped nextLine(): mixing nextInt() then nextLine() without flushing the newline.
- ❌ No prompt: the program just sits there waiting silently. Always print a prompt first.
- ❌ Assuming valid input: calling nextInt() on text crashes. Guard with hasNextInt().
- ❌ Creating a Scanner inside a loop: create one Scanner and reuse it; don't new Scanner(System.in) on every iteration.
📋 Quick Reference
| Code | Reads / Does | Returns |
|---|---|---|
| import java.util.Scanner; | Import the class (required) | — |
| new Scanner(System.in) | Create a keyboard scanner | Scanner |
| nextLine() | The whole rest of the line | String |
| next() | One word (token) | String |
| nextInt() | A whole number | int |
| nextDouble() | A decimal number | double |
| nextBoolean() | true / false | boolean |
| hasNextInt() | Peek: is the next token an int? | boolean |
| hasNextLine() | Peek: is there another line? | boolean |
| close() | Release the scanner when done | void |
| nextLine() after nextInt() | Extra call to flush leftover newline | String (often "") |
| nextInt() on text | Bad input crashes | throws InputMismatchException |
| while (!hasNextInt()) next(); | Validate: skip bad tokens | loop until valid |
🎉 Lesson Complete!
Your programs can now talk to people. You can import and create a Scanner, read lines, words, ints and doubles, dodge the leftover-newline trap, and validate input with hasNextInt() so a typo never crashes your program.
Practice quiz
Why must you import Scanner but not String or System?
- Scanner is a third-party library
- String and System are keywords
- Scanner lives in java.util, which is not auto-imported; String and System are in java.lang which is
- Scanner does not need importing either
Answer: Scanner lives in java.util, which is not auto-imported; String and System are in java.lang which is. Core classes in java.lang are imported automatically. Scanner is in java.util, so you must add import java.util.Scanner; or the compiler can't find the symbol.
The user types "Mary Jane" and presses Enter. What does scanner.next() return?
- "Mary"
- "Mary Jane"
- "Jane"
- An empty string
Answer: "Mary". next() reads a single whitespace-delimited token, stopping at the first space, so it returns "Mary". nextLine() would return the whole line.
What is the difference between next() and nextLine()?
- next() reads a whole line; nextLine() reads one word
- They are identical
- next() reads numbers only
- next() reads one whitespace-delimited token; nextLine() reads the rest of the line including spaces
Answer: next() reads one whitespace-delimited token; nextLine() reads the rest of the line including spaces. next() reads one word and stops at whitespace; nextLine() reads everything up to the newline. Use nextLine() for full names or addresses.
After int age = scanner.nextInt(); with the user typing 40 + Enter, what does the very next scanner.nextLine() return?
- "40"
- An empty string
- The next line of input
- null
Answer: An empty string. nextInt() leaves the trailing newline in the buffer, so the next nextLine() reads that leftover newline and returns an empty string immediately - the famous gotcha.
What happens if the user types text when your code calls scanner.nextInt()?
- It throws an InputMismatchException and the program crashes
- It returns 0
- It silently skips the input
- It returns the text as a String
Answer: It throws an InputMismatchException and the program crashes. nextInt() on non-numeric input throws InputMismatchException. Guard it with hasNextInt() first and discard bad tokens with next().
How do you fix the skipped-nextLine() newline bug?
- Use two Scanners
- Avoid nextInt() entirely
- Add an extra scanner.nextLine() after nextInt()/nextDouble() to swallow the leftover newline
- Call scanner.close() between reads
Answer: Add an extra scanner.nextLine() after nextInt()/nextDouble() to swallow the leftover newline. After a nextInt() or nextDouble() that is followed by a nextLine(), add one extra scanner.nextLine() to consume the dangling newline.
What does scanner.hasNextInt() do?
- Reads and returns the next int
- Peeks at the next token without consuming it, returning true only if it could be read as an int
- Throws if the next token is not an int
- Closes the scanner
Answer: Peeks at the next token without consuming it, returning true only if it could be read as an int. hasNextInt() peeks without consuming, returning true only if the next token is a valid int. Loop on it to validate input before calling nextInt().
Which method reads a decimal number like 1.82 from the keyboard?
- nextInt()
- nextLine()
- next()
- nextDouble()
Answer: nextDouble(). nextDouble() reads and returns a double. nextInt() reads a whole number; nextLine()/next() read text.
Why use System.out.print (no ln) for a prompt before reading input?
- It is required by Scanner
- So the cursor stays on the same line as the user's typing
- println does not work with Scanner
- It reads input automatically
Answer: So the cursor stays on the same line as the user's typing. print keeps the cursor on the same line, so the prompt and the user's typed answer sit together, which reads more naturally.
What is true about scanner.close() on a Scanner wrapping System.in?
- It is forbidden
- It reopens System.in
- Closing it also closes System.in, so don't create another Scanner on System.in afterward
- It must be called before every read
Answer: Closing it also closes System.in, so don't create another Scanner on System.in afterward. Closing a Scanner on System.in also closes System.in, so a second Scanner created afterward will fail. Close it once when you're done reading.
Continue this course
- Previous: Loops
- Next: The Math Class — Math.abs, pow, sqrt, round, random and more
- Quick reference: Java cheat sheet
Frequently asked questions
Why do I need to import Scanner but not String or System?
String, System, Integer and other core classes live in java.lang, which is imported automatically into every program. Scanner lives in the java.util package, which is not auto-imported, so you must add import java.util.Scanner; at the top of the file. If you forget it, the compiler reports that it cannot find the symbol 'Scanner'.
What is the difference between next() and nextLine()?
next() reads a single whitespace-delimited token (one word), stopping at the next space, tab, or newline. nextLine() reads everything up to and including the next newline — the whole rest of the line, spaces included. Use nextLine() for full names or addresses; use next() for single words.
Why does my nextLine() get skipped after nextInt()?
nextInt() reads the number but leaves the trailing newline character in the buffer. The very next nextLine() then reads that leftover newline and returns an empty string immediately. The fix is to add an extra scanner.nextLine() right after nextInt()/nextDouble() to consume the dangling newline before reading a real line.
What happens if the user types text when I call nextInt()?
nextInt() throws an InputMismatchException and your program crashes. To handle it gracefully, check scanner.hasNextInt() first and only call nextInt() when it returns true, otherwise discard the bad input with scanner.next() and ask again. That pattern is shown in the robust-input example.
Do I really need to call scanner.close()?
It is good practice to close any Scanner you create, especially one wrapping a file, to release the underlying resource. For System.in in a short program it matters less, but closing it is the tidy habit. Note: closing a Scanner on System.in also closes System.in, so don't create a second one afterward.