Java Utility Library

Java Scanner - hasNextShort() Method



The java.util.Scanner.hasNextShort() method returns true if the next token in the scanner's input can be interpreted as a short value in the default radix using the nextShort() method. The scanner does not advance past any input.

Syntax

public boolean hasNextShort()

Parameters

No parameter is required.

Return Value

Returns true if and only if the scanner's next token is a valid short value.

Exception

Throws IllegalStateException, if the scanner is closed.

Example:

In the example below, the java.util.Scanner.hasNextShort() method is used to check whether the scanner's next token is a valid short 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 a short
      //if yes, prints short value
      if(MyScan.hasNextShort())
        System.out.println("Short value is: "+ MyScan.nextShort());
      //if the next token 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