Java Utility Library

Java Scanner - nextBigInteger() Method



The java.util.Scanner.nextBigInteger() method is used to scan the next token of the input as a BigInteger. If the next token matches the Integer regular expression defined above then the token is converted into a BigInteger value as if by removing all group separators, mapping non-ASCII digits into ASCII digits via the Character.digit, and passing the resulting string to the BigInteger(String, int) constructor with the specified radix.

Syntax

public BigInteger nextBigInteger(int radix)

Parameters

radix Specify the radix used to interpret the token.

Return Value

Returns the BigInteger scanned from the input.

Exception

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

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

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

The output of the above code will be:

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

❮ Java.util - Scanner