hasNext(Pattern): This method is available in java.util.Scanner class of Java.
Syntax:
boolean java.util.Scanner.hasNext(Pattern pattern)
This method takes one argument. This method returns true if the next complete token matches the specified pattern.
Parameters: One parameter is required for this method.
pattern: the pattern to scan for.
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;import java.util.regex.Pattern;public class ScannerhasNext2 {public static void main(String[] args) {String source = "Hello World";Scanner scanner = new Scanner(source);Pattern pattern = Pattern.compile("[a-z]");System.out.println(scanner.hasNext(pattern));scanner.close();}}
Output:
false
Approach 2: IllegalStateException
Java
import java.util.Scanner;import java.util.regex.Pattern;public class ScannerhasNext2 {public static void main(String[] args) {String source = "Hello World";Scanner scanner = new Scanner(source);Pattern pattern = Pattern.compile("[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)
No comments:
Post a Comment