Scanner hasNext(String) in Java

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

Syntax:

boolean java.util.Scanner.hasNext(String pattern)

This method takes one argument. This method returns true if the next token matches the pattern constructed from the specified string.

Parameters: One parameter is required for this method.

pattern: a string specifying the pattern to scan.

Returns: true if and only if this scanner has another token matching the specified pattern.

Throws:

IllegalStateException - if this scanner is closed

Approach 1: When no exception

Java

import java.util.Scanner;

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

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

        String pattern = "[a-z]";
        System.out.println(scanner.hasNext(pattern));
        scanner.close();
    }
}

Output:

false


Approach 2: IllegalStateException

Java

import java.util.Scanner;

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

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

        String pattern = "[a-z]";
        scanner.close();
        System.out.println(scanner.hasNext(pattern));

    }
}

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.hasNext(Scanner.java:1540) at java.base/java.util.Scanner.hasNext(Scanner.java:1507)


No comments:

Post a Comment