Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Scanner nextLine() Method

$
0
0

1. Overview

In this tutorial, we'll briefly look at the nextLine() method of java.util.Scanner class. Furthermore, we'll see an example of its usage.

2. Scanner.nextLine()

The nextLine() method of the java.util.Scanner class scans from the current position until it finds a line separator delimiter. The method returns the String from the current position to the end of the line. Consequently, after the operation, the position of the scanner is set to the beginning of the next line that follows the delimiter.

The method will search through the input data looking for a line separator. It may scan all of the input data searching for the line to skip if no line separators are present.

The signature of the nextLine() method is:

public String nextLine()

The method takes no parameters. It returns the current line, excluding any line separator at the end.

Let's look at its usage:

try (Scanner scanner = new Scanner("Scanner\nTest\n")) {
    assertEquals("Scanner", scanner.nextLine());
    assertEquals("Test", scanner.nextLine());
}

As we have seen, the method returns the input from the current scanner position until the line separator is found:

try (Scanner scanner = new Scanner("Scanner\n")) {
    scanner.useDelimiter("");
    scanner.next();
    assertEquals("canner", scanner.nextLine());
}

In the above example, the call to next() returns ‘S' and advances the scanner position to point to ‘c'. Therefore, when we call nextLine() method it returns the input from the current scanner position until it finds a line separator.

The nextLine() method throws two types of checked exceptions.

Firstly, when no line separator is found, it throws NoSuchElementException:

@Test(expected = NoSuchElementException.class)
public void whenReadingLines_thenThrowNoSuchElementException() {
    try (Scanner scanner = new Scanner("")) {
        scanner.nextLine();
    }
}

Secondly, it throws IllegalStateException if the scanner is closed:

@Test(expected = IllegalStateException.class)
public void whenReadingLines_thenThrowIllegalStateException() {
    Scanner scanner = new Scanner("");
    scanner.close();
    scanner.nextLine();
}

3. Conclusion

In this quick article, we looked at the nextLine() method of Java's Scanner class. Furthermore, we looked at its usage in a simple Java program. Finally, we looked at the exceptions that are thrown by the method and sample code illustrating it.

As always, the full source code of the working examples is available over on GitHub.


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>