Flash cards
Review the key moves
What is the main idea behind Java Scanner hasNext() Method?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
// ___ a scanner object Scanner myObj = new Scanner("A string to scan");Put the learning moves in the order that makes the concept easiest to apply.
❮ Scanner Methods
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.
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. |
❮ Scanner Methods