User Input (Scanner)
So far your programs have worked with values you typed directly into the code. But real programs need to respond to the user — asking for a name, a number, a choice.
Java's Scanner class is how you read input from the keyboard. It's the standard tool for every beginner program that needs user interaction.
👉 What you'll learn here:
- ›How to set up Scanner in your program
- ›Reading Strings, integers, doubles, and characters
- ›Reading multiple inputs
- ›The common
nextLine()bug and how to fix it - ›Building a complete interactive program
🧘 Scanner is simple — but one tricky detail trips up almost every beginner.
The nextLine() bug (covered later in this page) causes programs to seemingly skip input. You'll hit it eventually. Reading this page first saves you the frustration of debugging it without knowing what's happening.
Setting Up Scanner
Scanner lives in the java.util package. Before using it, you must import it at the top of your file, and then create a Scanner object.
1import java.util.Scanner; // ← Step 1: import at the very top
2
3public class InputDemo {
4 public static void main(String[] args) {
5
6 Scanner scanner = new Scanner(System.in); // ← Step 2: create Scanner
7
8 // ... read input here ...
9
10 scanner.close(); // ← Step 3: close when done (good practice)
11 }
12}Breaking down Scanner scanner = new Scanner(System.in):
- ›
Scanner— the class type fromjava.util - ›
scanner— the name you give your Scanner object (any name works) - ›
new Scanner(System.in)— creates a Scanner connected to the keyboard (System.in= standard input)
💡 import must be the first line in your file, before the class declaration. If you forget it, the compiler says: error: cannot find symbol — Scanner.
Reading a String — next() and nextLine()
Scanner has two methods for reading text:
| Method | Reads | Stops at |
|---|---|---|
next() | One word | Whitespace (space, tab, enter) |
nextLine() | A full line | Enter key |
next() — reads one word:
1Scanner scanner = new Scanner(System.in);
2
3System.out.print("Enter your first name: ");
4String name = scanner.next();
5
6System.out.println("Hello, " + name + "!");Input / Output:
Enter your first name: Arjun
Hello, Arjun!
If the user types Arjun Kumar, next() only captures Arjun. The Kumar remains in the buffer.
nextLine() — reads the whole line:
1Scanner scanner = new Scanner(System.in);
2
3System.out.print("Enter your full name: ");
4String fullName = scanner.nextLine();
5
6System.out.println("Hello, " + fullName + "!");Input / Output:
Enter your full name: Arjun Kumar
Hello, Arjun Kumar!
💡 Which to use: Use nextLine() when the input might contain spaces (names, sentences, addresses). Use next() when you expect a single word with no spaces.
Reading Numbers
Scanner has dedicated methods for reading different numeric types.
Reading an int — nextInt()
1Scanner scanner = new Scanner(System.in);
2
3System.out.print("Enter your age: ");
4int age = scanner.nextInt();
5
6System.out.println("You are " + age + " years old.");Input / Output:
Enter your age: 22
You are 22 years old.
Reading a double — nextDouble()
1Scanner scanner = new Scanner(System.in);
2
3System.out.print("Enter the price: ");
4double price = scanner.nextDouble();
5
6System.out.println("Price with tax: ₹" + (price * 1.18));Input / Output:
Enter the price: 250.50
Price with tax: ₹295.59
Reading a long — nextLong()
1Scanner scanner = new Scanner(System.in);
2
3System.out.print("Enter your phone number: ");
4long phone = scanner.nextLong();
5
6System.out.println("Phone: " + phone);All Scanner Input Methods
| Method | Type Read | Example Input |
|---|---|---|
next() | String (one word) | Arjun |
nextLine() | String (full line) | Arjun Kumar |
nextInt() | int | 25 |
nextDouble() | double | 3.14 |
nextLong() | long | 9876543210 |
nextFloat() | float | 2.5 |
nextBoolean() | boolean | true |
Reading a Single Character
Scanner doesn't have a nextChar() method. To read a single character, read a String and extract the first character:
1Scanner scanner = new Scanner(System.in);
2
3System.out.print("Enter your grade (A/B/C): ");
4char grade = scanner.next().charAt(0); // read word, take first character
5
6System.out.println("Your grade is: " + grade);Input / Output:
Enter your grade (A/B/C): A
Your grade is: A
charAt(0) gets the character at position 0 (the first character) of the String.
Reading Multiple Inputs
You can call Scanner methods multiple times to read several values:
1Scanner scanner = new Scanner(System.in);
2
3System.out.print("Enter your name: ");
4String name = scanner.nextLine();
5
6System.out.print("Enter your age: ");
7int age = scanner.nextInt();
8
9System.out.print("Enter your GPA: ");
10double gpa = scanner.nextDouble();
11
12System.out.println("--- Student Profile ---");
13System.out.println("Name: " + name);
14System.out.println("Age: " + age);
15System.out.println("GPA: " + gpa);Input / Output:
Enter your name: Priya Sharma
Enter your age: 20
Enter your GPA: 9.2
--- Student Profile ---
Name: Priya Sharma
Age: 20
GPA: 9.2
The nextLine() Bug — The Most Common Scanner Problem
This is the bug that confuses almost every Java beginner. Understanding it once means you'll never be confused by it again.
The problem:
1Scanner scanner = new Scanner(System.in);
2
3System.out.print("Enter your age: ");
4int age = scanner.nextInt();
5
6System.out.print("Enter your name: ");
7String name = scanner.nextLine(); // ← BUG: this seems to be skipped!
8
9System.out.println("Name: " + name);
10System.out.println("Age: " + age);What happens:
Enter your age: 22
Enter your name: ← appears instantly — input skipped!
Name:
Age: 22
Why it happens:
When you type 22 and press Enter, Scanner reads 22 for nextInt() — but the Enter key itself (\n) stays in the input buffer. When nextLine() runs next, it immediately reads that leftover \n and returns an empty String — never waiting for you to type anything.
The fix — consume the leftover newline:
1Scanner scanner = new Scanner(System.in);
2
3System.out.print("Enter your age: ");
4int age = scanner.nextInt();
5
6scanner.nextLine(); // ← consume the leftover newline character
7
8System.out.print("Enter your name: ");
9String name = scanner.nextLine(); // ← now works correctly
10
11System.out.println("Name: " + name);
12System.out.println("Age: " + age);Now it works correctly:
Enter your age: 22
Enter your name: Priya Sharma
Name: Priya Sharma
Age: 22
⚠️ Rule: After any nextInt(), nextDouble(), nextLong(), or nextFloat() call, add scanner.nextLine() before the next nextLine() call. This clears the leftover newline from the buffer.
Validating Input — Checking Before Reading
What if the user types letters when you expect a number? Scanner throws an InputMismatchException. You can check what's coming before reading it:
1Scanner scanner = new Scanner(System.in);
2
3System.out.print("Enter a number: ");
4
5if (scanner.hasNextInt()) {
6 int number = scanner.nextInt();
7 System.out.println("You entered: " + number);
8} else {
9 System.out.println("That's not a valid number!");
10 scanner.next(); // consume the invalid input
11}| Method | Checks For |
|---|---|
hasNext() | Any token available |
hasNextLine() | A line available |
hasNextInt() | An integer available |
hasNextDouble() | A double available |
A Complete Interactive Program
Here's a practical program that uses everything covered on this page:
1import java.util.Scanner;
2
3public class StudentRegistration {
4 public static void main(String[] args) {
5
6 Scanner scanner = new Scanner(System.in);
7
8 System.out.println("=== Student Registration ===");
9 System.out.println();
10
11 // Read full name (may contain spaces)
12 System.out.print("Full name: ");
13 String name = scanner.nextLine();
14
15 // Read age (int)
16 System.out.print("Age: ");
17 int age = scanner.nextInt();
18 scanner.nextLine(); // consume leftover newline
19
20 // Read GPA (double)
21 System.out.print("GPA (0-10): ");
22 double gpa = scanner.nextDouble();
23 scanner.nextLine(); // consume leftover newline
24
25 // Read department (may contain spaces)
26 System.out.print("Department: ");
27 String dept = scanner.nextLine();
28
29 // Read grade (single char)
30 System.out.print("Grade (A/B/C/D): ");
31 char grade = scanner.next().charAt(0);
32
33 scanner.close();
34
35 // Display summary
36 System.out.println();
37 System.out.println("=== Registration Summary ===");
38 System.out.println("Name: " + name);
39 System.out.println("Age: " + age);
40 System.out.println("GPA: " + gpa);
41 System.out.println("Department: " + dept);
42 System.out.println("Grade: " + grade);
43
44 // Use input in logic
45 String status = (gpa >= 7.5) ? "Distinction" : "Pass";
46 System.out.println("Status: " + status);
47 }
48}Sample Input / Output:
=== Student Registration ===
Full name: Priya Sharma
Age: 20
GPA (0-10): 8.7
Department: Computer Science
Grade (A/B/C/D): A
=== Registration Summary ===
Name: Priya Sharma
Age: 20
GPA: 8.7
Department: Computer Science
Grade: A
Status: Distinction
Common Scanner Mistakes
1. Forgetting the import
1Scanner scanner = new Scanner(System.in); // ❌ error: cannot find symbolFix: Add import java.util.Scanner; as the first line of your file.
2. Using System.out.println instead of System.out.print for prompts
1System.out.println("Enter your name: "); // input appears on next line
2System.out.print("Enter your name: "); // input appears on same line ✅println adds a newline after the prompt — the user types on the next line which looks odd. Use print for prompts so the cursor stays on the same line as the question.
3. Not handling the nextLine() bug after numeric reads
1int age = scanner.nextInt();
2String name = scanner.nextLine(); // ❌ reads empty string
3
4int age = scanner.nextInt();
5scanner.nextLine(); // consume \n
6String name = scanner.nextLine(); // ✅ works correctly4. Reading a number but user types a String
1int age = scanner.nextInt(); // user types "twenty" → InputMismatchExceptionFix: use hasNextInt() to check before reading, or use try/catch.
5. Closing Scanner connected to System.in
1scanner.close();
2// After this, System.in is also closed
3// Any subsequent Scanner(System.in) will failIn small programs, scanner.close() is fine. In larger programs with multiple methods, don't close it if other parts of the program might still need it.
Quick Reference
1import java.util.Scanner;
2
3Scanner sc = new Scanner(System.in);
4
5String word = sc.next(); // one word
6String line = sc.nextLine(); // full line
7int num = sc.nextInt(); // integer
8double d = sc.nextDouble(); // decimal
9long l = sc.nextLong(); // large integer
10char c = sc.next().charAt(0); // single character
11
12sc.nextLine(); // use after nextInt/nextDouble to clear buffer
13
14sc.close(); // close when doneThe 3 Things to Remember From This Page
- ›Import and create Scanner first —
import java.util.Scanner;at the top,Scanner scanner = new Scanner(System.in);inside main. Without the import, the compiler can't findScanner. - ›The
nextLine()bug — after anynextInt(),nextDouble(), or other numeric read, add a barescanner.nextLine()call before the nextnextLine(). This clears the leftover newline that would otherwise be read as empty input. - ›Use
printnotprintlnfor prompts —System.out.print("Enter name: ")keeps the cursor on the same line so the user types right after the question.printlnpushes them to the next line, which looks awkward.
Summary
- ›
Scannerreads keyboard input — importjava.util.Scannerand create withnew Scanner(System.in) - ›
next()reads one word,nextLine()reads an entire line including spaces - ›
nextInt(),nextDouble(),nextLong()read numeric types directly - ›Single character — no
nextChar()exists, usescanner.next().charAt(0)instead - ›
nextLine()bug — numeric reads leave\nin the buffer. Addscanner.nextLine()after any numeric read before the nextnextLine()call - ›Validation — use
hasNextInt(),hasNextDouble()to check input type before reading - ›
scanner.close()when done — good practice in small programs
What to Read Next
| Topic | Link |
|---|---|
| Variables — storing the values you read | Variables → |
| Data types — what types Scanner can read | Data Types → |
| Type casting — converting input types | Type Casting → |
| if/else — making decisions from input | if / else / else-if → |
| Exception handling — catching bad input | Exception Handling → |