Java Scanner - next() Method
The java.util.Scanner.next() method returns the next token if it matches the specified string. If the match is successful, the scanner advances past the input that matched the pattern.
Syntax
public String next(String pattern)
Parameters
pattern |
Specify a string specifying the pattern to scan. |
Return Value
Returns the next token.
Exception
- Throws NoSuchElementException, if no such tokens are available.
- Throws IllegalStateException, if this scanner is closed.
Example:
In the example below, the java.util.Scanner.next() method returns the next token if it matches the specified string.
import java.util.*; public class MyClass { public static void main(String[] args) { //String to scan String MyString = "Hello Cello Hullo Hallo World Jello"; //creating a Scanner Scanner MyScan = new Scanner(MyString); while(MyScan.hasNext()) { //print the next token if matches "Hello" if(MyScan.hasNext("Hello")) System.out.println(MyScan.next("Hello")); //print the next token if matches "World" else if(MyScan.hasNext("World")) System.out.println(MyScan.next("World")); //else move to the next token else MyScan.next(); } //close the scanner MyScan.close(); } }
The output of the above code will be:
Hello World
❮ Java.util - Scanner