GuzziTony
GuzziTony

Reputation: 49

Java Scanner nextBigDecimal throwing InputMismatchException exception

I wrote some simple Java code to take input from the console (using Eclipse 2016 IDE) to assist with iterating through a text file and outputting a file in SWIFT MT940 statement structure. For the statements opening balance I used the Scanner Class nextBigDecimal() method which worked fine in the past. I recently upgraded to Eclipse 2023-12 version and am using Azul Zulu JRE 1.8, in case any of this matters.

I recently had to dust off my program and noted when I enter a non decimal value (0, 9, 100 etc) it runs fine, but if I enter a decimal number (0.00, 99.01 etc) the java.util.InputMismatchException is thrown.I have read and re-read the documentation, about BigDecimal, Scanner, java.util.InputMismatchException and some related methods. Note adding setScale() does not seem to help.

The code snippet below results in the exception being thrown. Do note i tried some other random items like using a comma as a decimal, so I don't think this is some sort of regional setting.

        System.out.print("Enter opening balance (Use . for decimal.):\t");
        BigDecimal checkBalSign = scan.nextBigDecimal();

The Exception:

        Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextBigDecimal(Scanner.java:2740)
    at standardbank.TonyDen.Toolbox.MT940_Formatter.initialSetup(MT940_Formatter.java:137)

I fixed this with a work around:

        String decimalInput = scan.next();
        BigDecimal checkBalSign = new BigDecimal(decimalInput);

Just perplexed as to why this is happening? Note the same instance of Scanner is working fine with other setup input in the same program. I also tried a Scanner.reset() before the nextBigDecimal().

Upvotes: 0

Views: 65

Answers (0)

Related Questions