next(Pattern): This method is available in java.util.Scanner class of Java.
Syntax:
String java.util.Scanner.next(Pattern pattern)
This method takes one argument. This method returns the next token if it matches the specified pattern.
Parameters: One parameter is required for this method.
pattern: the pattern to scan for.
Returns: the next token.
Throws:
1. NoSuchElementException - if no more tokens are available.
2. IllegalStateException - if this scanner is closed
Approach 1: When no exception
Java
import java.util.Scanner;import java.util.regex.Pattern;public class Scannernext2 {public static void main(String[] args) {String source = "Hello World";Scanner scanner = new Scanner(source);Pattern pattern = Pattern.compile("..llo");System.out.println(scanner.next(pattern));scanner.close();}}
Output:
Hello
Approach 2: NoSuchElementException
Java
import java.util.Scanner;import java.util.regex.Pattern;public class Scannernext2 {public static void main(String[] args) {String source = "";Scanner scanner = new Scanner(source);Pattern pattern = Pattern.compile("..llo");System.out.println(scanner.next(pattern));scanner.close();}}
Output:
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Scanner.throwFor(Scanner.java:937) at java.base/java.util.Scanner.next(Scanner.java:1594)
Approach 3: IllegalStateException
Java
import java.util.Scanner;import java.util.regex.Pattern;public class Scannernext2 {public static void main(String[] args) {String source = "";Scanner scanner = new Scanner(source);Pattern pattern = Pattern.compile("..llo");scanner.close();System.out.println(scanner.next(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.next(Scanner.java:1573)
No comments:
Post a Comment