Java Scanner - hasNextInt() Method
The java.util.Scanner.hasNextInt() method returns true if the next token in the scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
Syntax
public boolean hasNextInt()
Parameters
No parameter is required.
Return Value
Returns true if and only if the scanner's next token is a valid int value.
Exception
Throws IllegalStateException, if the scanner is closed.
Example:
In the example below, the java.util.Scanner.hasNextInt() method is used to check whether the scanner's next token is a valid int value or not.
import java.util.*; public class MyClass { public static void main(String[] args) { //String to scan String MyString = "Hello World 10 + 20 = 30.0"; //creating a Scanner Scanner MyScan = new Scanner(MyString); while(MyScan.hasNext()) { //check if the next token is an int //if yes, prints int value if(MyScan.hasNextInt()) System.out.println("Int value is: "+ MyScan.nextInt()); //if the next token is not an int else System.out.println("No Int Value found: "+ MyScan.next()); } //close the scanner MyScan.close(); } }
The output of the above code will be:
No Int Value found: Hello No Int Value found: World Int value is: 10 No Int Value found: + Int value is: 20 No Int Value found: = No Int Value found: 30.0
❮ Java.util - Scanner