bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java Scanner hasNext() Method

Flash cards

Review the key moves

1/4
Core idea

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.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

// ___ a scanner object Scanner myObj = new Scanner("A string to scan");
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Use hasNext() to read every token in a string:
Definition and Usage
Java Scanner hasNext() Method

❮ 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

ParameterDescription
patternOptional. 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

Previous

Java Scanner findWithinHorizon() Method

Next

Java Scanner hasNextBoolean() Method