Java Utility Library

Java Scanner - nextLong() Method



The java.util.Scanner.nextLong() method is used to scan the next token of the input as a long. This method will throw InputMismatchException if the next token cannot be translated into a valid long value as described below. If the translation is successful, the scanner advances past the input that matched.

Syntax

public long nextLong(int radix)

Parameters

radix Specify the radix used to interpret the token.

Return Value

Returns the long scanned from the input.

Exception

  • Throws InputMismatchException, if the next token does not match the Long 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.nextLong() method is used to scan the next token of the input as a long.

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 long
      //print the long with radix 16
      if(MyScan.hasNextLong(16))
        System.out.println("Long value is: "+ MyScan.nextLong(16));
      //if the next is not a long
      else
        System.out.println("No Long Value found: "+ MyScan.next());
    }

    //close the scanner
    MyScan.close();
  }
}

The output of the above code will be:

No Long Value found: Hello
No Long Value found: World
Long value is: 16
No Long Value found: +
Long value is: 32
No Long Value found: =
No Long Value found: 30.0

❮ Java.util - Scanner