Java Scanner next() Method
Example
Display the next token from the scanner:
// Create a scanner object
Scanner myObj = new Scanner("A string to scan");
// Output the next token
System.out.println(myObj.next());
Definition and Usage
The next()
method returns a string containing the next token in the scanner.
If the pattern parameter is used, then it will throw an exception when the token does not match the regular expression specified by the parameter.
Learn more about the regular expressions in our Java RegEx tutorial.
What is a token?
A token is a sequence of characters separated from other tokens by delimiters. The default delimiter is a block of whitespace characters but it can be changed with the useDelimiter()
method.
Syntax
One of the following:
public String next()
public String next(Pattern pattern)
public String next(String pattern)
Parameter Values
Parameter | Description |
---|---|
pattern | Optional. Specifies a regular expression that the next token must match in order to be valid. |
Technical Details
Returns: | A String containing the next token in the scanner. |
---|---|
Throws: |
InputMismatchException - If the token does not match the regular expression.NoSuchElementException - If there are no more tokens in the scanner.IllegalStateException - If the scanner has been closed.
|