Java Scanner hasNext() Method
Example
Use hasNext() to read every token in a string:
// Create a scanner object
Scanner myObj = new Scanner("A string to scan");
// Read every token
while(myObj.hasNext()) {
System.out.println(myObj.next());
}
Definition and Usage
The hasNext()
method returns true if there is another token available in the scanner.
If the pattern parameter is used, then it only returns true if the next token matches 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 boolean hasNext()
public boolean hasNext(Pattern pattern)
public boolean hasNext(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 boolean value which is true if another token is available and matches the regular expression provided by the pattern parameter. |
---|---|
Throws: | IllegalStateException - If the scanner has been closed. |