Flash cards
Review the key moves
What is the main idea behind Java Scanner next() 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
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.
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. |
❮ Scanner Methods