Home » Java programming language

Java Scanner hasNextLong() Method with Example

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

Scanner Class hasNextLong() method

Syntax:

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

Example:

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

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

public class HasNextLong {
 public static void main(String[] args) {
  String str = "Java Programming! 3 * 8= 24";
  Long val = 124582456l;

  str = str + val;

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

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

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

  // Scanner closed
  sc.close();
 }
}

Output

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


Comments and Discussions!

Load comments ↻





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