Sub topic 4
Reading a Whole Line
This chapter assumes that you know basic Java syntax, can compile and run a program, and understand variables, methods, and String. It also assumes that you have created a Scanner for reading console input.
A line is all the text typed before the user presses Enter. A Scanner reads a complete line with nextLine().
Using `nextLine()`
Create a Scanner around System.in, which represents standard input. Then call nextLine() when you want the user's complete response.
import java.util.Scanner;
public class Greeting {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("What is your full name? ");
String name = input.nextLine();
System.out.println("Hello, " + name + "!");
}
}If the user types Ada Lovelace, the variable name contains the complete string "Ada Lovelace". Spaces inside the response are preserved.
The method returns an empty string when the user presses Enter without typing anything. It does not return null for a blank line.
What `nextLine()` consumes
nextLine() reads characters up to the next line terminator. It consumes that line terminator but does not include it in the returned string.
For example, suppose the input is:
red green blueThis call returns the entire text:
String colors = input.nextLine();The result is "red green blue", not only "red".
A line can contain spaces, punctuation, or no characters:
System.out.print("Enter a sentence: ");
String sentence = input.nextLine();
if (sentence.isEmpty()) {
System.out.println("You entered a blank line.");
} else {
System.out.println("Length: " + sentence.length());
}isEmpty() checks whether the string has zero characters. If you want to reject input that contains only spaces, use trim() or strip() before checking it.
String response = input.nextLine().strip();
if (response.isEmpty()) {
System.out.println("Please enter some text.");
}strip() removes leading and trailing whitespace. It does not remove spaces between words.
Check for the end of input
Interactive users usually provide a line and press Enter. A program can also receive input from a file or a pipe. In that situation, input can end without another line being available.
Use hasNextLine() before calling nextLine() when the input may end:
import java.util.Scanner;
public class LineCounter {
public static void main(String[] args) {
int count = 0;
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
String line = input.nextLine();
if (!line.isBlank()) {
count++;
}
}
System.out.println("Nonblank lines: " + count);
}
}hasNextLine() checks whether another line exists without consuming it. The loop then calls nextLine() exactly when a line is available.
Avoid accidental empty lines
A common source of confusion occurs when a program reads a number with nextInt() and then immediately calls nextLine(). The number method leaves the line terminator waiting in the input. The following nextLine() consumes that remaining part of the line, which may be empty.
The usual solution is to call nextLine() once to consume the rest of the current line before reading the next real line. The details of this mixed-input problem are covered in the next chapter.
Exercise
Which method should you call to read the complete response New York City, including its spaces?
Show answer
Call nextLine(). It returns the text up to the next line terminator as one String.