Javatpoint Logo
Javatpoint Logo

Java Scanner hasNextInt() Method

The hasNextInt() method of Java Scanner class is used to check if the next token in this scanner's input can be interpreted as an int value using the nextInt() method. There is two different types of Java hasNextInt() method which can be differentiated depending on its parameter. These are:

  1. Java Scanner hasNextInt() Method
  2. Java Scanner hasNextInt(int radix) Method

hasNextInt() Method:

This Java Scanner class method is used to check if the next token in this scanner's input can be interpreted as an int value or not in the default radix using the nextInt() method. It returns true if it can be interprated as an int value otherwise reurns false.

hasNextInt(int radix) Method:

This is an inbuilt method of Java Scanner class which is used to check if the next token in this scanner's input can be interpreted as an int value or not in the specified radix using the nextInt() method.

Syntax

Following is the declaration of hasNextInt() method:

Parameter

DataType Parameter Description Required/Optional
int radix It is used to interpret the token as an int value. Required

Returns

The hasNextInt() method returns true if and only if this scanner's next token is a valid int value.

Exceptions

IllegalStateException- It throws this exception if the innvocation is done after the scanner has been closed.

IllegalArgumentException- It throws this exception if the specified radix is out of range.

Compatibility Version

Java 1.5 and above

Example 1

Output:

Found Int Value: 21

Example 2

Output:

Found Int Value: false
Scan Token: Hello
Found Int Value: false
Scan Token: World!
Found Int Value: true
Scan Token: 12
Found Int Value: false
Scan Token: +
Found Int Value: false
Scan Token: 13.0
Found Int Value: false
Scan Token: =
Found Int Value: true
Scan Token: 15
Found Int Value: false
Scan Token: 2.123

Example 3

Output:

Please enter value: 12345
Your entered value: 12345

Please enter value: 123.45
Please entered the Integer value. 

Example 4

Output:

Found :85
Not Found :B3
Found :-37
Not Found :-7
Not Found :1D

Example 5

Output:

Exception in thread "main" java.lang.IllegalArgumentException: radix:598670
	at java.base/java.util.Scanner.setRadix(Scanner.java:1368)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2254)
	at myPackage.ScannerHasNextIntExample5.main(ScannerHasNextIntExample5.java:10)
Next TopicJava Scanner Class



Help Others, Please Share

facebook twitter pinterest