Java Utility Library

Java Scanner - nextBigDecimal() Method



The java.util.Scanner.nextBigDecimal() method is used to scan the next token of the input as a BigDecimal. If the next token matches the Decimal regular expression defined above then the token is converted into a BigDecimal 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 BigDecimal(String) constructor.

Syntax

public BigDecimal nextBigDecimal()

Parameters

No parameter is required.

Return Value

Returns the BigDecimal scanned from the input.

Exception

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

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 BigDecimal
      if(MyScan.hasNextBigDecimal())
        System.out.println("BigDecimal value is: "+ MyScan.nextBigDecimal());
      //if the next is not a BigDecimal
      else
        System.out.println("No BigDecimal Value found: "+ MyScan.next());
    }

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

The output of the above code will be:

No BigDecimal Value found: Hello
No BigDecimal Value found: World
BigDecimal value is: 10
No BigDecimal Value found: +
BigDecimal value is: 20
No BigDecimal Value found: =
BigDecimal value is: 30.0

❮ Java.util - Scanner