0

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().

2
  • 2
    I suspect "Use . for decimal" - Scanner uses the default Locale when reading decimals - try using a , instead of . (at least for testing); or try scan.useLocale(Locale.ROOT); Commented Mar 13, 2024 at 16:30
  • What happens with new BigDecimal(scan.next()); and new BigDecimal(scan.next().trim());? Have you changed the delimiter? Commented Mar 13, 2024 at 16:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.