Sub topic 2
The Leftover Newline Pitfall
This chapter assumes basic Java syntax, console execution, String and primitive types, and basic exception handling.
Mixing Token and Line Reads
Scanner.nextInt() reads an integer token but leaves the line terminator in the input. nextLine() then reads that remaining, empty part of the line instead of waiting for new text.
import java.util.Scanner;
public class MixedReads {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Count: ");
int count = in.nextInt();
in.nextLine(); // consume the leftover newline
System.out.print("Title: ");
String title = in.nextLine();
System.out.println(count + " x " + title);
}
}The extra nextLine() is intentional. It discards the rest of the line after nextInt().
Validating Input
Before calling nextInt(), use hasNextInt() to check the next token. It does not consume the token. If the token is invalid, next() consumes it so the loop can continue.
import java.util.Scanner;
public class SafeInt {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
while (!in.hasNextInt()) {
if (!in.hasNext()) {
System.out.println("Input ended.");
return;
}
System.out.println("Not a number: " + in.next());
System.out.print("Enter a number: ");
}
int number = in.nextInt();
System.out.println("You entered " + number);
}
}Calling nextInt() without checking can throw InputMismatchException. Checking first is usually clearer for interactive programs.
Reading Until Input Ends
For input streams that end, loop while the desired read is available. End of input is often called EOF.
import java.util.Scanner;
public class SumAll {
public static void main(String[] args) {
int sum = 0;
try (Scanner in = new Scanner(System.in)) {
while (in.hasNextInt()) {
sum += in.nextInt();
}
}
System.out.println("Sum: " + sum);
}
}The try block closes the scanner at the end. Closing a Scanner created from System.in also closes System.in, so do this only when the program is finished using standard input.
Exercise
Why does a direct call to nextLine() after nextInt() often return an empty string?
Show answer
nextInt() leaves the line terminator unread, so nextLine() consumes that terminator and returns the rest of the current line, which is empty.