Java Scanner - nextShort() Method
The java.util.Scanner.nextShort() method is used to scan the next token of the input as a short. An invocation of this method of the form nextShort() behaves in exactly the same way as the invocation nextShort(radix), where radix is the default radix of this scanner.
Syntax
public short nextShort()
Parameters
No parameter is required.
Return Value
Returns the short scanned from the input.
Exception
- Throws InputMismatchException, if the next token does not match the Short regular expression, or is out of range.
- Throws NoSuchElementException, if input is exhausted.
- Throws IllegalStateException, if this scanner is closed.
Example:
In the example below, the java.util.Scanner.nextShort() method is used to scan the next token of the input as a short.
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()) { //if the next is a short if(MyScan.hasNextShort()) System.out.println("Short value is: "+ MyScan.nextShort()); //if the next is not a short else System.out.println("No Short Value found: "+ MyScan.next()); } //close the scanner MyScan.close(); } }
The output of the above code will be:
No Short Value found: Hello No Short Value found: World Short value is: 10 No Short Value found: + Short value is: 20 No Short Value found: = No Short Value found: 30.0
❮ Java.util - Scanner