Scanner nextLine() in Java

nextLine(): This method is available in java.util.Scanner class of Java.

Syntax:

String java.util.Scanner.nextLine()

This method advances this scanner past the current line and returns the input that was skipped.

Parameters: NA

Returns: the line that was skipped.

Throws:

1. NoSuchElementException - if no line was found.

2. IllegalStateException - if this scanner is closed

Approach 1: When no exception

Java

import java.util.Scanner;

public class ScannernextLine {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        System.out.println(scanner.nextLine());

        scanner.close();
    }
}

Output:

Hello World


Approach 2: NoSuchElementException 

Java

import java.util.Scanner;

public class ScannernextLine {
    public static void main(String[] args) {

        String source = "";
        Scanner scanner = new Scanner(source);

        System.out.println(scanner.nextLine());

        scanner.close();
    }
}

Output:

Exception in thread "main" java.util.NoSuchElementException: No line found at java.base/java.util.Scanner.nextLine(Scanner.java:1651)


Approach 3: IllegalStateException 

Java

import java.util.Scanner;

public class ScannernextLine {
    public static void main(String[] args) {

        String source = "Hello World";
        Scanner scanner = new Scanner(source);

        scanner.close();
        System.out.println(scanner.nextLine());

    }
}

Output:

Exception in thread "main" java.lang.IllegalStateException: Scanner closed at java.base/java.util.Scanner.ensureOpen(Scanner.java:1150) at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1781) at java.base/java.util.Scanner.nextLine(Scanner.java:1649)


No comments:

Post a Comment