Java User Input (Scanner Class)
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.
import java.util.Scanner; // ← Step 1: import at the very top
public class InputDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // ← Step 2: create Scanner
// ... read input here ...
scanner.close(); // ← Step 3: close when done (good practice)
}
}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:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your first name: ");
String name = scanner.next();
System.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:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your full name: ");
String fullName = scanner.nextLine();
System.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()
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("You are " + age + " years old.");Input / Output:
Enter your age: 22
You are 22 years old.
Reading a double — nextDouble()
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the price: ");
double price = scanner.nextDouble();
System.out.println("Price with tax: ₹" + (price * 1.18));Input / Output:
Enter the price: 250.50
Price with tax: ₹295.59
Reading a long — nextLong()
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your phone number: ");
long phone = scanner.nextLong();
System.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:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your grade (A/B/C): ");
char grade = scanner.next().charAt(0); // read word, take first character
System.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:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your GPA: ");
double gpa = scanner.nextDouble();
System.out.println("--- Student Profile ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.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:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // ← BUG: this seems to be skipped!
System.out.println("Name: " + name);
System.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:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
scanner.nextLine(); // ← consume the leftover newline character
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // ← now works correctly
System.out.println("Name: " + name);
System.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:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
if (scanner.hasNextInt()) {
int number = scanner.nextInt();
System.out.println("You entered: " + number);
} else {
System.out.println("That's not a valid number!");
scanner.next(); // consume the invalid input
}| 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:
import java.util.Scanner;
public class StudentRegistration {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("=== Student Registration ===");
System.out.println();
// Read full name (may contain spaces)
System.out.print("Full name: ");
String name = scanner.nextLine();
// Read age (int)
System.out.print("Age: ");
int age = scanner.nextInt();
scanner.nextLine(); // consume leftover newline
// Read GPA (double)
System.out.print("GPA (0-10): ");
double gpa = scanner.nextDouble();
scanner.nextLine(); // consume leftover newline
// Read department (may contain spaces)
System.out.print("Department: ");
String dept = scanner.nextLine();
// Read grade (single char)
System.out.print("Grade (A/B/C/D): ");
char grade = scanner.next().charAt(0);
scanner.close();
// Display summary
System.out.println();
System.out.println("=== Registration Summary ===");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("GPA: " + gpa);
System.out.println("Department: " + dept);
System.out.println("Grade: " + grade);
// Use input in logic
String status = (gpa >= 7.5) ? "Distinction" : "Pass";
System.out.println("Status: " + status);
}
}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
Scanner 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
System.out.println("Enter your name: "); // input appears on next line
System.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
int age = scanner.nextInt();
String name = scanner.nextLine(); // ❌ reads empty string
int age = scanner.nextInt();
scanner.nextLine(); // consume \n
String name = scanner.nextLine(); // ✅ works correctly4. Reading a number but user types a String
int age = scanner.nextInt(); // user types "twenty" → InputMismatchExceptionFix: use hasNextInt() to check before reading, or use try/catch.
5. Closing Scanner connected to System.in
scanner.close();
// After this, System.in is also closed
// 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
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
String word = sc.next(); // one word
String line = sc.nextLine(); // full line
int num = sc.nextInt(); // integer
double d = sc.nextDouble(); // decimal
long l = sc.nextLong(); // large integer
char c = sc.next().charAt(0); // single character
sc.nextLine(); // use after nextInt/nextDouble to clear buffer
sc.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
Practice Programs
Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.
Reads a single integer typed by the user and prints it back.
Reads a full line of text typed by the user and prints it back.
Reads a single decimal number typed by the user and prints it back.
Reads an int, a double, and a String from the console in a single program.
Reads an array's size and elements from the console.
Catches an InputMismatchException from reading the wrong type with Scanner.