Java User Input with Scanner
Read input from the console in Java using the Scanner class — nextInt, nextDouble, nextLine, and input validation.
For most beginner programs, the easiest way to read input from the keyboard is java.util.Scanner. It wraps System.in (the standard input stream) and gives you methods like nextInt, nextDouble, and nextLine. This chapter covers the Scanner API, the famous "Scanner skip a line" gotcha, and what to reach for once Scanner stops fitting.
Setting up a Scanner
Scanner lives in java.util, so you need an import:
import java.util.Scanner;
public class Greeter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("What is your name? ");
String name = in.nextLine();
System.out.println("Hello, " + name + "!");
}
}Scanner should be closed when you're done with it — but if you close a scanner over System.in, you also close standard input for the rest of the program. For short scripts it's fine to skip close(). For longer code, use try-with-resources for any scanners over files but not for System.in.
The reader methods
| Method | Reads |
|---|---|
nextLine() | the rest of the current line (excludes \n) |
next() | the next whitespace-delimited token |
nextInt() | the next token, parsed as int |
nextLong() | …as long |
nextDouble() | …as double |
nextBoolean() | …as boolean |
hasNext() | true if another token is available |
hasNextInt() | true if the next token is a valid int |
hasNextLine() | true if another line is available |
Use the hasNext... variants to validate input before consuming it.
A complete prompt loop
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("First number: ");
double a = in.nextDouble();
System.out.print("Second number: ");
double b = in.nextDouble();
System.out.println("Sum: " + (a + b));
}
}If the user types a non-number, nextDouble throws InputMismatchException. We'll cover handling that below.
The classic gotcha — nextInt leaves a newline behind
After nextInt() or nextDouble(), the scanner leaves the trailing newline in the buffer. The next nextLine() then returns an empty string:
System.out.print("age? ");
int age = in.nextInt(); // user types "30" then Enter
System.out.print("name? ");
String name = in.nextLine(); // returns "" — the leftover newline
String name2 = in.nextLine(); // returns the typed nameTwo common fixes:
- After
nextInt()/nextDouble(), callin.nextLine()to discard the rest of the line. - Use
nextLine()everywhere and parse the string yourself:
System.out.print("age? ");
int age = Integer.parseInt(in.nextLine().trim());The second style is cleaner once you start handling validation.
Validating with hasNext...
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
while (!in.hasNextInt()) {
System.out.print("That isn't an integer. Try again: ");
in.next(); // discard the bad token
}
int value = in.nextInt();
System.out.println("You entered: " + value);Reading until EOF
A common batch-processing pattern — read until the user types Ctrl+D (Linux/macOS) or Ctrl+Z then Enter (Windows):
Scanner in = new Scanner(System.in);
int total = 0;
while (in.hasNextInt()) {
total += in.nextInt();
}
System.out.println("Total: " + total);BufferedReader — when Scanner isn't fast enough
For competitive programming or anywhere you read tens of thousands of lines, BufferedReader is significantly faster than Scanner:
import java.io.BufferedReader;
import java.io.InputStreamReader;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int n = Integer.parseInt(line.trim());It's a little more code, but a 10–20× speedup is common.
System.console() — interactive sessions only
When the program is attached to a real terminal, System.console() returns a Console object with readLine and readPassword (which doesn't echo characters):
java.io.Console c = System.console();
if (c != null) {
String user = c.readLine("Username: ");
char[] pass = c.readPassword("Password: ");
// ... use pass ...
java.util.Arrays.fill(pass, ' '); // zero out the password buffer
}System.console() returns null when the program runs through an IDE that pipes stdin, so don't rely on it for general input.
A demonstration
The runnable code below uses System.in. The runner doesn't supply interactive input, so this version reads from a fixed string instead — close to how Scanner is normally used:
What's next
Part 2 finishes here. The next part — Java Control Flow — covers if/else, switch, and the loops that drive most program logic.
Practice
After calling scanner.nextInt(), why does a following scanner.nextLine() often return an empty string?