Reading input with Scanner
Read text and numbers from a source, and dodge the classic nextInt/nextLine trap.
Open this lesson in the learning hubKey points
new Scanner(System.in)reads the console. AScannerover aStringruns the same code in a test.nextLine()takes the rest of the line, whilenext()andnextInt()take one token.- Check before you read:
hasNextInt()avoids theInputMismatchExceptiona stray word would cause. nextInt()leaves the newline behind, so the nextnextLine()comes back empty. Read lines and parse them.- Reading past the end throws
NoSuchElementException, so drive the loop withhasNext(). - Close it with try-with-resources — but never close a
ScanneroverSystem.inwhile you still need input.
Example
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// A real program uses new Scanner(System.in). A String source keeps this demo repeatable.
String typed = "Ada\n36\nred green blue\n";
try (Scanner in = new Scanner(typed)) {
String name = in.nextLine();
int age = Integer.parseInt(in.nextLine());
System.out.println(name + " is " + age + " years old");
String[] colours = in.nextLine().split(" ");
System.out.println("read " + colours.length + " colours, first = " + colours[0]);
}
try (Scanner tokens = new Scanner("10 20 hello 30")) {
int total = 0;
while (tokens.hasNext()) {
if (tokens.hasNextInt()) {
total += tokens.nextInt();
} else {
System.out.println("not a number, skipping: " + tokens.next());
}
}
System.out.println("total of the numbers: " + total);
}
System.out.println("nextInt() leaves the newline behind - that is why a later nextLine() looks empty");
}
}
Guard every read with hasNextX, and prefer nextLine plus parse.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.