CKTIS / Java
Scanner — reading numbers and lines
java.util.Scanner reads text tokens and lines. Distinguish reading a number from reading the remainder of a line, and configure number formatting explicitly.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
new Scanner(source); scanner.nextInt(); scanner.nextDouble(); scanner.nextLine(); scanner.useLocale(Locale.US); scanner.close();java.util.Scanner separates tokens on whitespace by default. Scanner.nextInt() reads an int; Scanner.nextDouble() reads a double. Scanner.useLocale(Locale.US) selects number formatting with a decimal point.
Scanner.nextLine() returns the current line's remainder without its separator and advances. After a number, it may return an empty string. In the example, the first call skips the number line's remainder; the second reads the name.
An invalid numeric token causes InputMismatchException and remains unread; missing input causes NoSuchElementException. Reading may wait for input.
Scanner.close() also closes a source implementing Closeable, including System.in. try-with-resources closes automatically. Do not close shared input that will still be needed.
Examples
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try (Scanner scanner = new Scanner("3 2.5\nAda Lovelace\n")) {
scanner.useLocale(Locale.US);
int count = scanner.nextInt();
double value = scanner.nextDouble();
scanner.nextLine();
String name = scanner.nextLine();
System.out.println(count);
System.out.println(value);
System.out.println(name);
}
}
}Result
3 2.5 Ada Lovelace
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.
Sources
- java.util (Java SE 21 & JDK 21)
- Scanner (Java SE 21 & JDK 21)
- Official reference — docs.oracle.com: util / Scanner.html
- Official reference — docs.oracle.com: util / Scanner.html
- Official reference — docs.oracle.com: util / Scanner.html
- Official reference — docs.oracle.com: util / Scanner.html
- Official reference — docs.oracle.com: util / Scanner.html