Home » Java programming language

Java Scanner hasNextShort() Method with Example

Scanner Class hasNextShort() method: Here, we are going to learn about the hasNextShort() method of Scanner Class with its syntax and example.
Submitted by Preeti Jain, on March 26, 2020

Scanner Class hasNextShort() method

Syntax:

    public boolean hasNextShort();
    public boolean hasNextShort(int rad);
  • hasNextShort() method is available in java.util package.
  • hasNextShort() method is used to check whether this Scanner has next token in its input can be manipulated as a short value in the implicit radix or not.
  • hasNextShort(int rad) method is used to check whether this Scanner has next token in its input can be manipulated as a short value in the explicit radix(rad) or not.
  • These methods may throw an exception at the time of representing input as a short value.
    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, hasNextShort(),
    • It does not accept any parameter.
  • In the second case, hasNextShort(int rad),
    • int rad – represents the radix used to manipulate as a short value.

Return value:

In both the cases, the return type of the method is boolean, it returns true when this Scanner next input as a short valid value otherwise it returns false.

Example:

// Java program is to demonstrate the example
// of hasNextShort() method of Scanner

import java.util.*;
import java.util.regex.*;

public class HasNextShort {
 public static void main(String[] args) {
  String str = "Java Programming! 3 * 8= 24";
  Short val = 125;

  str = str + val;

  // Instantiates Scanner
  Scanner sc = new Scanner(str);

  while (sc.hasNext()) {
   // By using hasNextShort() method is to
   // check whether this object next token
   // represents short or not in the default 
   // radix
   boolean status = sc.hasNextShort();
   System.out.println("sc.hasNextShort(): " + status);

   // By using hasNextShort(radix) method is to
   // check whether this object next token
   // represents short in the given radix
   // or not
   status = sc.hasNextShort(4);
   System.out.println("sc.hasNextShort(2): " + status);
   sc.next();
  }
  // Scanner closed
  sc.close();
 }
}

Output

sc.hasNextShort(): false
sc.hasNextShort(2): false
sc.hasNextShort(): false
sc.hasNextShort(2): false
sc.hasNextShort(): true
sc.hasNextShort(2): true
sc.hasNextShort(): false
sc.hasNextShort(2): false
sc.hasNextShort(): false
sc.hasNextShort(2): false
sc.hasNextShort(): true
sc.hasNextShort(2): false


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.