Home »
Java programming language
Java Scanner hasNextInt() Method with Example
Scanner Class hasNextInt() method: Here, we are going to learn about the hasNextInt() method of Scanner Class with its syntax and example.
Submitted by Preeti Jain, on March 26, 2020
Scanner Class hasNextInt() method
Syntax:
public boolean hasNextInt();
public boolean hasNextInt(int rad);
- hasNextInt() method is available in java.util package.
- hasNextInt() method is used to check whether this Scanner has next token in its input can be manipulated as an int in the implicit radix (rad) or not.
- hasNextInt(int rad) method is used to check whether this Scanner has next token in its input can be manipulated as an int in the explicit or given radix (rad) or not.
- These methods may throw an exception at the time of representing input as an int.
IllegalStateException: This exception may throw when this Scanner is not opened.
- These are non-static methods, it is accessible with class object & if we try to access these methods with the class name then we will get an error.
Parameter(s):
-
In the first case, hasNextInt(),
- It does not accept any parameter.
-
In the second case, hasNextInt(int rad),
- int rad – represents the radix used to manipulate as an int.
Return value:
In both the cases, the return type of the method is boolean, it returns true when this Scanner next input as an int otherwise it returns false.
Example:
// Java program is to demonstrate the example
// of hasNextInt() method of Scanner
import java.util.*;
import java.util.regex.*;
public class HasNextInt {
public static void main(String[] args) {
String str = "Java Programming! 3 * 8= 24";
// Instantiates Scanner
Scanner sc = new Scanner(str);
while (sc.hasNext()) {
// By using hasNextInt() method is to
// check whether this object next token
// represents int or not in the default
// radix
boolean status = sc.hasNextInt();
System.out.println("sc.hasNextInt(): " + status);
// By using hasNextInt(radix) method is to
// check whether this object next token
// represents integer in the given radix
// or not
status = sc.hasNextInt(2);
System.out.println("sc.hasNextInt(2): " + status);
sc.next();
}
// Scanner closed
sc.close();
}
}
Output
sc.hasNextInt(): false
sc.hasNextInt(2): false
sc.hasNextInt(): false
sc.hasNextInt(2): false
sc.hasNextInt(): true
sc.hasNextInt(2): false
sc.hasNextInt(): false
sc.hasNextInt(2): false
sc.hasNextInt(): false
sc.hasNextInt(2): false
sc.hasNextInt(): true
sc.hasNextInt(2): false