Scanner hasNextLine() in Java

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

Syntax:

boolean java.util.Scanner.hasNextLine()

This method returns true if there is another line in the input of this scanner.

Parameters: NA

Returns: true if and only if this scanner has another line of input.

Throws:

IllegalStateException - if this scanner is closed

Approach 1: When no exception

Java

import java.util.Scanner;

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

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

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

        scanner.close();
    }
}

Output:

true


Approach 2: IllegalStateException 

Java

import java.util.Scanner;

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

        String source = "Hello World";
        Scanner scanner = new Scanner(source);
        scanner.close();
        System.out.println(scanner.hasNextLine());

    }
}

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.hasNextLine(Scanner.java:1610)


No comments:

Post a Comment