tokens(): This method is available in java.util.Scanner class of Java.
Syntax:
Stream<String> java.util.Scanner.tokens()
This method returns a stream of delimiter-separated tokens from this scanner.
Parameters: NA
Returns: a sequential stream of token strings.
Throws:
IllegalStateException - if this scanner is closed.
Approach 1: When no exception
Java
import java.util.Scanner;public class Scannertokens {public static void main(String[] args) {String source = "Hello World";Scanner scanner = new Scanner(source);System.out.println(scanner.tokens().count());scanner.close();}}
Output:
2
Approach 2: IllegalStateException
Java
import java.util.Scanner;public class Scannertokens {public static void main(String[] args) {String source = "Hello World";Scanner scanner = new Scanner(source);scanner.close();System.out.println(scanner.tokens().count());}}
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.tokens(Scanner.java:2829)
No comments:
Post a Comment