bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java Scanner hasNextInt() Method

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java Scanner hasNextInt() 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("An int is a number between -2,147,483,648 and 2,147,483,647");
3Order

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

Print the value of every integer in the string:
Definition and Usage
Java Scanner hasNextInt() Method

❮ Scanner Methods

Example

Print the value of every integer in the string:

// Create a scanner object Scanner myObj = new Scanner("An int is a number between -2,147,483,648 and 2,147,483,647");
// Print the value of every int in the scanner
while (myObj.hasNext()) {
 if (myObj.hasNextInt()) {
 System.out.println(myObj.nextInt());
 } else {
 myObj.next();
}
}

Definition and Usage

The hasNextInt() method returns true if the next token represents a number that can be stored by the int data type, which is any whole number between -2,147,483,648 and 2,147,483,647.

The scanner is able to interpret digit groupings, such as using a comma for separating groups of 3 digits. The format of the groupings depends on the locale settings of the scanner, which can be changed with the useLocale() method.

If the radix parameter is used, then it interprets numbers using the radix. For example, a radix of 16 would interpret numbers as hexadecimal (digits 0 to 9 and A to F). If the radix parameter is not used then it interprets numbers using the scanner's radix, which is 10 by default but it can be changed with the useRadix() method.

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 hasNextInt()
public boolean hasNextInt(int
radix )

Parameter Values

ParameterDescription
radixOptional. Specifies the radix used to interpret numbers. The radix specifies how many different symbols can be used to represent a digit in a number.

Technical Details

Returns:A boolean value which is true if the next token represents an int value.
Throws:IllegalStateException - If the scanner has been closed.

❮ Scanner Methods

Previous

Java Scanner hasNextFloat() Method

Next

Java Scanner hasNextLine() Method