3

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
  • 3
    Could be the problem described in https://stackoverflow.com/questions/48244290/exception-in-thread-main-java-util-inputmismatchexception-using-nextfloat – MDK Nov 01 '20 at 19:41
  • 2
    [Here's](https://stackoverflow.com/questions/28997094/scanner-next-throws-java-util-inputmismatchexception-for-float-but-not-for-in) a similar question, but I'm not sure why it works in Java 12. – user Nov 01 '20 at 19:42
  • 4
    Most likely, it's a Locale related issue. Did you try to specify locale for Scanner: `Scanner scanner = new Scanner(System.in).useLocale(Locale.US);` ? – Nowhere Man Nov 01 '20 at 19:44
  • @MDK thank you man, this really helped, though I still don't understand why is it like that. –  Nov 01 '20 at 19:47
  • @AlexRudenko I did, I used Locale.US –  Nov 01 '20 at 19:48
  • 1
    @Alex please post your comment as an answer. – Bohemian Nov 01 '20 at 20:22
  • @Bill what is your normal locale? I suspect it has to do with the decimal separator. As in the linked question. – matt Nov 01 '20 at 20:36

1 Answers1

1

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.

Nowhere Man
  • 19,170
  • 9
  • 17
  • 42