Java Scanner hasNextInt() MethodThe 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:
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. SyntaxFollowing is the declaration of hasNextInt() method: Parameter
ReturnsThe hasNextInt() method returns true if and only if this scanner's next token is a valid int value. ExceptionsIllegalStateException- 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 VersionJava 1.5 and above Example 1Output: Found Int Value: 21 Example 2Output: 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 3Output: Please enter value: 12345 Your entered value: 12345 Please enter value: 123.45 Please entered the Integer value. Example 4Output: Found :85 Not Found :B3 Found :-37 Not Found :-7 Not Found :1D Example 5Output: 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
|