Java Scanner Class
What Scanner Does
java.util.Scanner reads text and breaks it into tokens — pieces separated by a delimiter, which is whitespace by default — and converts tokens into Java types: nextInt(), nextDouble(), nextBoolean(), nextBigDecimal() and so on. It can read from System.in, a file, a String or any InputStream or Reader.
That makes it the most convenient tool for interactive console programs and for small, simply structured text inputs, where you'd otherwise have to read lines and parse them yourself:
Scanner sc = new Scanner(System.in);
int age = sc.nextInt(); // reads the next token and converts it to int
Its convenience comes at a cost: Scanner uses regular expressions internally and is much slower than BufferedReader for large inputs, and its mix of token-based and line-based methods has a well-known trap (covered below). For big files and fast parsing, use BufferedReader; for interactive input and quick parsing, Scanner is ideal.
Creating a Scanner
Scanner keyboard = new Scanner(System.in); // standard input
Scanner file = new Scanner(Path.of("scores.txt"), StandardCharsets.UTF_8); // a file (throws IOException)
Scanner text = new Scanner("PEN-01 12 4.50"); // a String
Scanner encoded = new Scanner(inputStream, StandardCharsets.UTF_8); // any stream, explicit charset
Constructors without a charset argument — for System.in, a Path or any stream — decode bytes with the platform default charset. That is UTF-8 everywhere since Java 18, but on Java 17 and earlier it depended on the operating system, so pass a charset explicitly when reading files in code that must run on older versions.
Scanner implements Closeable. Close scanners over files you opened, preferably with try-with-resources. Don't close a scanner that wraps System.in: closing it closes System.in itself, and any later attempt to read the keyboard — even with a new Scanner — fails with NoSuchElementException. Create one keyboard scanner for the whole program and leave it open.
Reading Different Types
import java.util.Scanner;
public class S1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Age: ");
int age = sc.nextInt();
System.out.print("Height in metres: ");
double height = sc.nextDouble();
System.out.println();
System.out.println(name + " is " + age + " years old and " + height + " m tall");
}
}
A session in a terminal (the user's typing appears after each prompt):
Name: Asha Rao
Age: 27
Height in metres: 1.62
Asha Rao is 27 years old and 1.62 m tall
| Method | Reads | Example input → result |
|---|---|---|
next() | The next token as a String | Asha Rao → "Asha" |
nextLine() | The rest of the current line, without the line terminator | Asha Rao → "Asha Rao" |
nextInt(), nextLong(), nextShort(), nextByte() | The next token as an integer type | 27 → 27 |
nextDouble(), nextFloat() | The next token as a floating-point number | 1.62 → 1.62 |
nextBoolean() | true or false, ignoring case | TRUE → true |
nextBigDecimal(), nextBigInteger() | Exact decimal / arbitrarily large integer | 250.50 → 250.50 |
print(notprintln) keeps the cursor on the prompt line, so the user types right after the prompt.nextLine()is used for the name because it can contain spaces;next()would return onlyAsha.- Each
nextXxx()method blocks until enough input is available — for keyboard input, until the user presses Enter.
The nextInt / nextLine Trap
This program asks for a number and then a line of text:
import java.util.Scanner;
public class Pitfall {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Quantity: ");
int qty = sc.nextInt();
System.out.print("Delivery note: ");
String note = sc.nextLine();
System.out.println();
System.out.println("qty=" + qty + ", note=\"" + note + "\"");
}
}
In a terminal, the user types 3, presses Enter — and the program doesn't wait for the note at all:
Quantity: 3
Delivery note:
qty=3, note=""
Why it happens: the input is 3\n. nextInt() reads the token 3 and stops right after it, leaving the line terminator \n unread. nextLine() then reads "the rest of the current line", which is empty, and returns "" immediately.
Two reliable fixes:
- Read every line with
nextLine()and parse it yourself — the approach most experienced developers use for interactive input:
import java.util.Scanner;
public class Fixed {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Quantity: ");
int qty = Integer.parseInt(sc.nextLine().strip());
System.out.print("Delivery note: ");
String note = sc.nextLine();
System.out.println();
System.out.println("qty=" + qty + ", note=\"" + note + "\"");
}
}
Quantity: 3
Delivery note: Leave at the gate
qty=3, note="Leave at the gate"
- Consume the leftover line terminator with an extra
sc.nextLine();afternextInt(). This works, but it's easy to forget when code changes, and it also silently discards anything else the user typed on that line.
The rule: don't mix token methods (nextInt, next, nextDouble) and nextLine on the same scanner without thinking about where the line terminator is.
Validating Input
If the next token doesn't match the requested type, nextInt() throws InputMismatchException — and the bad token stays in the scanner. A loop that catches the exception and calls nextInt() again reads the same bad token forever. Two safe approaches: check first with a hasNextXxx() method, or read the whole line and parse it, as here:
import java.util.Scanner;
public class Valid {
static int readInt(Scanner sc, String prompt, int min, int max) {
while (true) {
System.out.print(prompt);
if (!sc.hasNextLine()) throw new IllegalStateException("no more input");
String text = sc.nextLine().strip();
System.out.println(text);
try {
int value = Integer.parseInt(text);
if (value >= min && value <= max) return value;
System.out.println(" please enter a number from " + min + " to " + max);
} catch (NumberFormatException e) {
System.out.println(" \"" + text + "\" is not a whole number");
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int seats = readInt(sc, "Seats (1-6): ", 1, 6);
System.out.println("booked " + seats + " seats");
}
}
Output with the input lines two, 9 and 4 piped in (printf 'two\n9\n4\n' | java Valid):
Seats (1-6): two
"two" is not a whole number
Seats (1-6): 9
please enter a number from 1 to 6
Seats (1-6): 4
booked 4 seats
hasNextLine()returnsfalsewhen the input has ended (Ctrl+D / end of a piped file). Without this check,nextLine()would throwNoSuchElementException; here the method reports it clearly instead of looping forever.- The line is echoed with
System.out.println(text)only so that piped input shows up in the output; in an interactive terminal you'd remove that line, because the terminal already displays what the user types. - Two kinds of validation: the format (
"two"isn't a number) and the range (9is outside 1–6). Both repeat the prompt. - Wrapping this in a reusable
readIntmethod keeps the rest of the program free of validation loops.
The hasNext family — hasNext(), hasNextInt(), hasNextDouble(), hasNextLine() and others — checks without consuming anything, so it's safe to call before deciding which next method to use.
Tokens, Delimiters and Parsing Strings
import java.util.*;
public class Tokens {
public static void main(String[] args) {
Scanner words = new Scanner(" Java is\tfun \n to learn ");
List<String> list = new ArrayList<>();
while (words.hasNext()) list.add(words.next());
System.out.println("tokens: " + list);
Scanner mixed = new Scanner("PEN-01 12 4.50 true");
String sku = mixed.next();
int qty = mixed.nextInt();
double price = mixed.nextDouble();
boolean gift = mixed.nextBoolean();
System.out.println(sku + " x" + qty + " @ " + price + " gift=" + gift);
Scanner csv = new Scanner("Asha,91,Chennai\nRavi,78,Madurai\n").useDelimiter(",|\\R");
while (csv.hasNext()) {
String name = csv.next();
int score = csv.nextInt();
String city = csv.next();
System.out.println(name + " (" + city + ") scored " + score);
}
System.out.println("sum via tokens(): " + new Scanner("10 20 30").tokens().mapToInt(Integer::parseInt).sum());
try {
new Scanner("ten").nextInt();
} catch (InputMismatchException e) {
System.out.println("InputMismatchException for \"ten\"");
}
try {
new Scanner("").next();
} catch (NoSuchElementException e) {
System.out.println("NoSuchElementException on empty input");
}
}
}
Output (in an English locale):
tokens: [Java, is, fun, to, learn]
PEN-01 x12 @ 4.5 gift=true
Asha (Chennai) scored 91
Ravi (Madurai) scored 78
sum via tokens(): 60
InputMismatchException for "ten"
NoSuchElementException on empty input
- Default delimiter: any run of whitespace — spaces, tabs and newlines — so extra spacing disappears and tokens can span lines.
- Mixed types: reading tokens in the right order with the matching
nextmethods parses a whole record from one line. useDelimiter(regex)changes what separates tokens.",| 0 R"means "a comma or a line break" (\Rmatches\n,\r\nand\r), so each comma-separated field becomes a token across both lines. This works for simple CSV, but not for quoted fields containing commas — use a CSV library for real CSV files.tokens()(Java 9+) returns the remaining tokens as aStream<String>;findAll(regex)returns all matches of a pattern.- Exceptions:
InputMismatchExceptionwhen a token doesn't fit the type;NoSuchElementExceptionwhen there are no more tokens. Both are unchecked, so the compiler won't remind you to handle them.
Locale and Number Formats
nextInt, nextDouble and nextBigDecimal interpret numbers according to the scanner's locale, which defaults to the user's system locale:
import java.util.*;
public class Loc {
public static void main(String[] args) {
System.out.println("ROOT: " + new Scanner("1234.5").useLocale(Locale.ROOT).nextDouble());
System.out.println("GERMANY \"1234,5\": " + new Scanner("1234,5").useLocale(Locale.GERMANY).nextDouble());
System.out.println("GERMANY hasNextDouble(\"1234.5\"): " + new Scanner("1234.5").useLocale(Locale.GERMANY).hasNextDouble());
System.out.println("US \"1,234.5\": " + new Scanner("1,234.5").useLocale(Locale.US).nextDouble());
}
}
Output:
ROOT: 1234.5
GERMANY "1234,5": 1234.5
GERMANY hasNextDouble("1234.5"): false
US "1,234.5": 1234.5
In a German locale the comma is the decimal separator and the dot is a grouping separator, so 1234,5 is valid and 1234.5 isn't. Locale-aware parsing is right for numbers a person types in their own format. For data with a fixed format — files, protocols, tests — always set useLocale(Locale.ROOT) (or Locale.US), otherwise the same program and the same input give different results on a machine with a different language setting. Integer.parseInt and Double.parseDouble are never locale-dependent, which is another argument for reading lines and parsing them yourself.
Practical Example: A Command-Driven Expense Tracker
Many console tools read commands line by line: a word that selects an action, followed by arguments. A common, robust design uses one scanner for lines and a second scanner per line to split that line into tokens — so a malformed command can never leave the main input in a strange position.
import java.math.BigDecimal;
import java.util.*;
public class Expenses {
record Expense(String category, BigDecimal amount, String note) { }
public static void main(String[] args) {
Scanner sc = new Scanner(System.in).useLocale(Locale.ROOT);
List<Expense> expenses = new ArrayList<>();
while (true) {
System.out.print("> ");
if (!sc.hasNextLine()) break;
String line = sc.nextLine().strip();
System.out.println(line);
if (line.isEmpty()) continue;
Scanner cmd = new Scanner(line).useLocale(Locale.ROOT);
String action = cmd.next().toLowerCase();
switch (action) {
case "add" -> {
String category = cmd.hasNext() ? cmd.next() : null;
if (category == null || !cmd.hasNextBigDecimal()) {
System.out.println(" usage: add CATEGORY AMOUNT [NOTE]");
continue;
}
BigDecimal amount = cmd.nextBigDecimal();
String note = cmd.hasNextLine() ? cmd.nextLine().strip() : "";
expenses.add(new Expense(category, amount, note));
System.out.println(" added " + amount + " to " + category);
}
case "summary" -> {
Map<String, BigDecimal> byCat = new TreeMap<>();
for (Expense e : expenses) byCat.merge(e.category(), e.amount(), BigDecimal::add);
byCat.forEach((c, total) -> System.out.printf(" %-10s %10s%n", c, total));
System.out.printf(" %-10s %10s%n", "TOTAL",
expenses.stream().map(Expense::amount).reduce(BigDecimal.ZERO, BigDecimal::add));
}
case "quit" -> {
System.out.println(" bye");
return;
}
default -> System.out.println(" unknown command: " + action);
}
}
System.out.println("(end of input)");
}
}
Output with these commands piped in: add food 250.50 lunch with team, add travel 1200, add food 99.5, add books, list, summary, quit:
> add food 250.50 lunch with team
added 250.50 to food
> add travel 1200
added 1200 to travel
> add food 99.5
added 99.5 to food
> add books
usage: add CATEGORY AMOUNT [NOTE]
> list
unknown command: list
> summary
food 350.00
travel 1200
TOTAL 1550.00
> quit
bye
Step by step:
- The outer scanner only reads lines.
hasNextLine()ends the loop cleanly when input runs out;quitends it withreturn. (Theprintln(line)echo is there only to make piped input visible.) - A new scanner per line parses the command. The first token selects the action, using a
switchon strings. addvalidates before reading. If the category is missing or the next token isn't a valid decimal (hasNextBigDecimal()), it prints usage andcontinues to the next prompt. Because the line has its own scanner, nothing is left over to confuse the next command.- The note is the rest of the line: after the amount,
nextLine()on the line scanner returns everything remaining (" lunch with team"), stripped of the leading space. This is the token-then-line mix working for you, on a scanner that contains only one line. - Money uses
BigDecimal, so250.50 + 99.5is exactly350.00(the scale of the result is the larger of the two).Locale.ROOTguarantees the dot is the decimal separator regardless of the system language. Map.mergetotals by category in aTreeMap(sorted output), andreducecomputes the grand total.
The same structure — read a line, split it into a command and arguments, validate, dispatch — is how shells, database consoles and admin tools are built.