next(String): This method is available in java.util.Scanner class of Java.
Syntax:
String java.util.Scanner.next(String pattern)
This method takes one argument. This method returns the next token if it 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: the next token.
Throws:
1. NoSuchElementException - if no such tokens are available.
2. IllegalStateException - if this scanner is closed
Approach 1: When no exception
Java
import java.util.Scanner;public class Scannernext3 {public static void main(String[] args) {String source = "Hello World";Scanner scanner = new Scanner(source);String pattern = "..llo";System.out.println(scanner.next(pattern));scanner.close();}}
Output:
Hello
Approach 2: NoSuchElementException
Java
import java.util.Scanner;public class Scannernext3 {public static void main(String[] args) {String source = "";Scanner scanner = new Scanner(source);String pattern = "..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) at java.base/java.util.Scanner.next(Scanner.java:1525)
Approach 3: IllegalStateException
Java
import java.util.Scanner;public class Scannernext3 {public static void main(String[] args) {String source = "Hello World";Scanner scanner = new Scanner(source);String pattern = "..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) at java.base/java.util.Scanner.next(Scanner.java:1525)
No comments:
Post a Comment