Reading from the console in Java has one trap that catches every beginner. The method next() and the method nextLine() do not take the same amount of input, and mixing them in the wrong order gives you a program that appears to skip a line for no reason at all.
The previous lesson in this module covered "What Operators Does Java Support and When Are They Useful?", and this is the last lesson in the module. The next module starts with "How Do if, else and Logical Operators Branch Your Code?", which moves on from reading input to making decisions with it.
How do I read a line?
Create a Scanner over System.in and call nextLine() on it.
import java.util.Scanner;
public class Greeting {
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);
in.close();
}
}
The scanner reads from the standard input of the program, which is the place where whatever a person types arrives. Closing the scanner when you are finished is good habit, because a scanner over System.in closes standard input for the whole program, and that matters if you read again later. In a small program it is not a practical problem, but it is worth writing the habit from the start.
Why does my input get skipped?
Here is the trap in full. The method next() reads one word and leaves the line break behind in the input. The method nextLine() reads the rest of the line, including that line break.
import java.util.Scanner;
public class Trap {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Age: ");
int age = in.nextInt(); // reads "25" and leaves the newline behind
System.out.print("City: ");
String city = in.nextLine(); // gives back "", because the newline was left behind
System.out.println("age=" + age + " city=[" + city + "]");
}
}
Type 25 and press enter, then type Paris, and the program prints city=[]. The city was swallowed by the line break that was left behind. There are three ways out, and the choice is yours.
- Read everything as text with
nextLine()and convert the text yourself. This is the most predictable option. - Mix the two methods in the right order. Either read the number last, or eat the leftover line break with a call to
in.nextLine()after a numeric read. - Use
useDelimiter("\s+")when every piece of input is separated by spaces.
Scanner in = new Scanner(System.in);
System.out.print("Age: ");
int age = in.nextInt();
in.nextLine(); // eat the leftover newline
System.out.print("City: ");
String city = in.nextLine(); // now it works
Can the scanner read typed values directly?
Yes, and it is convenient when the input is well formed. There is nextInt(), nextLong(), nextDouble(), nextBoolean() and next() for a single word. The risk is that they throw an error when the input is not what they expected.
import java.util.Scanner;
public class Typed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try {
System.out.print("Quantity: ");
int quantity = in.nextInt();
System.out.println("got " + quantity);
} catch (java.util.InputMismatchException e) {
System.out.println("That was not a whole number.");
}
in.close();
}
}
An InputMismatchException is an unchecked error, so bad input makes the program die with a stack trace unless you deal with it. A safer pattern is to ask whether the input is valid before you read it.
Scanner in = new Scanner(System.in);
System.out.print("Quantity: ");
if (in.hasNextInt()) {
int quantity = in.nextInt();
System.out.println("got " + quantity);
} else {
System.out.println("that was not a whole number");
}
How do I read several lines?
A loop over hasNextLine() reads an unknown number of lines until the input ends.
import java.util.Scanner;
public class Lines {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int lineNumber = 1;
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println(lineNumber + ": " + line);
lineNumber = lineNumber + 1;
}
in.close();
}
}
For a large amount of input, a scanner is not the right tool. It works through the text one character at a time, and it is noticeably slower than buffered reading. A BufferedReader with readLine() is the standard alternative for anything substantial.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
How do I prompt without breaking the input?
Printing a prompt and then reading on the same line looks like the obvious way to do it, and it works, as long as the prompt ends with a space and the reader knows to type on that line. The other way is to print the prompt, let the person press enter, and then read the whole line as text. That second way is more predictable, especially when the input might be pasted in from somewhere else.
import java.util.Scanner;
public class Prompt {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("What is your name?");
String name = in.nextLine();
System.out.println("How old are you?");
String ageText = in.nextLine();
int age = Integer.parseInt(ageText);
System.out.println(name + " is " + age);
in.close();
}
}
Reading the age as text and converting it yourself is the pattern that never trips over the newline problem, because every read takes a whole line. It also gives you a place to deal with a bad value. The method Integer.parseInt throws a NumberFormatException on text that is not a number, and catching that at the boundary is much better than letting it escape.
Does the same work apply to files?
Yes, and this is where a scanner really earns its keep. Point one at a file and you get exactly the same set of methods for a completely different source. That is how you write code that reads from the console in a test and from a data file in production.
import java.nio.file.Path;
import java.util.Scanner;
Scanner in = new Scanner(Path.of("data.txt"));
while (in.hasNextLine()) {
System.out.println(in.nextLine().toUpperCase());
}
in.close();
Swap System.in for a path and everything else stays exactly the same. That is the real lesson of the scanner. It is a reader that does not care where the text comes from, and the console is simply the easiest place to reach.
What should you use for a large amount of input?
A Scanner is convenient, and it is the right choice for a program that asks a person a few questions. It is not the right choice for a file with a million lines, because a scanner parses with regular expressions and makes more work for itself than the stream underneath needs. For bulk input, a BufferedReader with readLine is leaner and just as easy to use.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BulkReading {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
int count = 0;
while ((line = reader.readLine()) != null) {
count = count + 1;
}
reader.close();
System.out.println("lines read : " + count);
}
}
Two habits make this safe. Read the line into a variable and compare it with null, rather than comparing it with an empty string, because null is the sign that the input has ended. And close the reader when you are done with it, or wrap it in a try-with-resources block so that it closes itself even when something goes wrong.
There is a middle ground worth knowing about. A scanner also has a method called useDelimiter, which lets you treat a whole file as one long stream of pieces separated by commas or tabs. That is the quick way to read a simple file of comma separated values without bringing in a real parsing library, and it is still faster than splitting the file line by line.
Quick reference
- The method
next()reads one word and leaves the line break behind, whilenextLine()reads the whole line. - Mixing the two in the wrong order quietly skips a line.
- Typed reads throw an InputMismatchException on bad input, so check with
hasNextInt()first. - Close the scanner when you are finished with it.
- For a large amount of input, use a BufferedReader instead.
Try it yourself: write a program that asks for a name and an age and then prints a greeting that includes both of them. Get the order wrong on purpose first, so that you can see the empty line bug for yourself, and then fix it in the two ways that were described above and check that both of them behave correctly.