Javatpoint Logo
Javatpoint Logo

Java Scanner hasNextShort() Method

The hasNextShort() is a Java Scanner class method which is used to check the next token in this scanner's input can be interpreted as a short value in the default radix or not. It returns true if it is interprated as a short value, otherwise returns false. There is two different types of Java hasNextShort() method which can be differentiated depending on its parameter. These are:

  • Java Scanner hasNextShort() Method
  • Java Scanner hasNextShort(int radix) Method

hasNextShort() Method:

This is a Java Scanner class method which is used to check the next token in this scanner's input can be interpreted as a short value in the default radix using the nextShort() method.

hasNextShort(int radix) Method:

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

Syntax

Following is the declaration of hasNextShort() method:

Parameter

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

Returns

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

Exceptions

IllegalStateException- This method throws 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:

Is Short Value: false
Scan String: Instagram.com
Is Short Value: true
Scan String: 1

Example 2

Output:

Found a short: 22
Found a short: 23
Found a short: -11
Found a short: -7

Example 3

Output:

Exception in thread "main" java.lang.IllegalArgumentException: radix:5967597
	at java.base/java.util.Scanner.setRadix(Scanner.java:1368)
	at java.base/java.util.Scanner.hasNextShort(Scanner.java:2041)
	at myPackage.ScannerHasNextShortExample3.main(ScannerHasNextShortExample3.java:12)

Example 4

Output:

Give me a bunch of numbers in a line (or 'exit')
1 3 6 6
Sum is 16

Next TopicJava Scanner Class



Help Others, Please Share

facebook twitter pinterest