Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This was written in java 12 but if I run it on java 15, it throws an exception error [duplicate]

Tags:

java

I used scanner.NextFloat() but if I try to input float number it throws an error, however if I type int numbers it successfully converts into a double or float, what's the problem? Written in java 12, I'm trying to run it on java 15.

import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Principal: ");
        float principal = scanner.nextFloat();

        System.out.print("Annual Interest Rate: ");
        float annualInterestRate = scanner.nextFloat();
}
}
Principal: 88888
Annual Interest Rate: 9.8
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.nextFloat(Scanner.java:2496)
    at com.company.Main.main(Main.java:16)

Process finished with exit code 1

1 Answers

This seems to be a Locale related issue.

Specifying locale for Scanner:

Scanner scanner = new Scanner(System.in).useLocale(Locale.US);

should help resolve scanning float/double numbers using . as a decimal separator.

like image 195
Nowhere Man Avatar answered Dec 23 '25 13:12

Nowhere Man



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!