Sub topic 4
Reading a whole line
This chapter assumes you can compile and run a Java program from the command line and use String, loops and try/catch. It also assumes you have created a Scanner on System.in and read single tokens with next and nextInt.
Token reading splits input on whitespace. That is the wrong tool when one answer can contain spaces, such as a full name, a book title or a sentence. For those you read a whole line with nextLine.
What nextLine does
Scanner.nextLine() returns the rest of the current line. It stops at the next line terminator and returns the text before it. It then moves past the terminator, and the terminator is not part of the returned string.
import java.util.Scanner;
public class Greeter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Name: ");
String name = in.nextLine();
System.out.print("Age: ");
int age = in.nextInt();
System.out.println(name + " is " + age);
}
}If you type Ada Lovelace and press Enter, name holds Ada Lovelace, spaces included. next() would have returned only Ada. The nextInt call that follows reads one integer token for the age.
A terminal sends your input to the program only when you press Enter. So nextLine returns once you finish a line, not as you type.
Tokens and lines compared
Suppose the input is the single line Ada Lovelace (two spaces before and after the text).
| Call | Returns | Notes |
|---|---|---|
| `next()` | `Ada` | Skips leading whitespace and stops at the next whitespace. |
| `nextLine()` | ` Ada Lovelace ` | Keeps leading and trailing spaces. Drops only the terminator. |
| `nextInt()` | throws `InputMismatchException` | The token `Ada` is not an integer. |
nextLine does not trim anything. If you want clean text, call trim() yourself, or strip() if you need to handle Unicode whitespace.
What counts as a line terminator
A Scanner recognizes these line separators:
\n, used on Linux and macOS.\r\n, used on Windows.\r, a bare carriage return.\u2028,\u2029and\u0085, the Unicode line and paragraph separators and the next-line character.
You do not need to know which one your platform uses. A program that reads a file written on Windows gets the same lines as one written on Linux. You can see this by scanning a string instead of the keyboard:
import java.util.Scanner;
public class LineDemo {
public static void main(String[] args) {
String text = "first\r\nsecond\n\nfourth";
Scanner sc = new Scanner(text);
int n = 1;
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(n + ": [" + line + "]");
n++;
}
}
}The output is:
1: [first]
2: [second]
3: []
4: [fourth]Three details are worth noting:
- The blank line between
secondandfourthcomes back as an empty string. Pressing Enter on its own is a valid line. - The last line has no terminator, and
nextLinestill returns it. - If the text ended with
\n, you would not get a fifth, empty line. A trailing terminator ends the last line. It does not start a new one.
The program never calls nextLine on its own. It checks hasNextLine first, which the next section covers.
Reading the rest of a line
nextLine starts from the scanner's current position, not from the start of the line. After a token read, the position is in the middle of the line, so nextLine returns only what is left.
import java.util.Scanner;
public class RestOfLine {
public static void main(String[] args) {
Scanner in = new Scanner("hello world\nsecond line\n");
String first = in.next();
String rest = in.nextLine();
String next = in.nextLine();
System.out.println("[" + first + "]");
System.out.println("[" + rest + "]");
System.out.println("[" + next + "]");
}
}The output is:
[hello]
[ world]
[second line]next consumed hello and stopped before the space. nextLine then returned world, with the leading space, and consumed the terminator.
The same mechanism causes the leftover-newline problem. If nextInt reads the last token on a line, nextLine returns the empty remainder of that line. The next chapter covers the pitfall in detail. For now, remember that mixing token reads and line reads needs care.
Checking before you read
Calling nextLine when no line is left throws java.util.NoSuchElementException with the message No line found. This happens when:
- standard input comes from a file or pipe that has run out, or
- the user ends the input from the keyboard. On Linux and macOS this is Ctrl+D. On Windows it is Ctrl+Z followed by Enter.
hasNextLine() returns true if another line can be read. It does not consume anything, and it may block while it waits for you to type. This makes the standard line-reading loop safe:
import java.util.Scanner;
public class NumberedLines {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = 1;
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println(n + ": " + line);
n++;
}
}
}Try it with piped input:
printf 'one\n\nthree\n' | java NumberedLinesThis prints 1: one, 2: and 3: three. The blank line appears as line 2, as in the earlier demo. Reading until the input ends is covered in its own chapter, so the details of end-of-input handling are left for there.
An edge case with empty input
An input of zero bytes has no lines, so hasNextLine() is false and the loop body never runs. An input of a single \n has one line, which is empty. Your program should not treat the two cases alike if the difference matters.
Turning a line into values
A common pattern is to read a whole line and then process it yourself. This gives you control over errors. A failed nextInt leaves the bad token in the input, while a failed Integer.parseInt on a line you already read leaves nothing stuck.
import java.util.Scanner;
public class LineSum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Numbers separated by spaces: ");
String line = in.nextLine().trim();
int sum = 0;
if (!line.isEmpty()) {
for (String part : line.split("\\s+")) {
sum += Integer.parseInt(part);
}
}
System.out.println("Sum: " + sum);
}
}The program trims the line first. Without trim(), a leading space would make split produce an empty first element, and Integer.parseInt("") would throw NumberFormatException. The isEmpty check handles a blank line, where split would otherwise return one empty string.
For one number per line, the usual form is Integer.parseInt(in.nextLine().trim()). It fails with NumberFormatException on bad text. The next chapters show how to catch that and ask again.
Common errors
- Forgetting that the terminator is removed.
nextLinenever returns\n. If you print lines withSystem.out.print, add the newline yourself. - Expecting trimmed text. A user who types a trailing space gets it back. Comparing
"yes"with"yes "fails. Usetrim()before comparing. - Comparing with
==.line == "quit"compares references and is almost always false. Useline.equals("quit"), or"quit".equals(line). - Calling
nextLinewith nothing left. The result isNoSuchElementException: No line found. Guard withhasNextLine(). - Mixing
nextIntandnextLinewithout handling the leftover terminator. ThenextLinereturns an empty string immediately. The next chapter fixes this. - Using more than one
ScanneronSystem.in. Each scanner buffers input it has read ahead. Text buffered by the first scanner is invisible to the second. Create oneScannerand pass it to the methods that need it.
Exercise
A program reads with Scanner in = new Scanner("alpha beta\ngamma\n"); and then runs String a = in.next(); String b = in.nextLine(); String c = in.nextLine();. What are the values of a, b and c, and what happens if the program then calls in.nextLine() a third time?
Show answer
a is alpha. b is beta with a leading space, because next stopped before the space and nextLine returned the rest of the first line. c is gamma. A third nextLine throws NoSuchElementException with the message No line found, because all the input has been consumed. A hasNextLine() check would return false first.
Exercise
Write a loop that reads lines from standard input and stops when the user types quit in any letter case, ignoring spaces around it. It must also stop cleanly if the input ends first, and it must print the number of lines read before stopping, not counting quit itself.
Show answer
Use hasNextLine as the loop condition and compare with equalsIgnoreCase on a trimmed line:
int count = 0;
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String line = in.nextLine().trim();
if (line.equalsIgnoreCase("quit")) {
break;
}
count++;
}
System.out.println("Lines: " + count);
The hasNextLine check ends the loop when the input runs out, so no NoSuchElementException occurs. Trimming handles spaces around the word, and equalsIgnoreCase handles QUIT and Quit.