Search code examples
javamismatch

Dots are returning me MisMatch exceptions, even i'm using Locale.US


My program is returning Mismatch exception after I tried to input number with dot, on next.Double(). I'm using Locale.US.

Scanner sc = new Scanner(System.in);
Locale.setDefault(Locale.US);

double nota1, nota2, resultado;

nota1 = sc.nextDouble();
nota2 = sc.nextDouble();

resultado = nota1 + nota2;

if (resultado < 60.0) {
    System.out.println("NOTA FINAL = " + resultado);
    System.out.println("REPROVADO");
}
else {
    System.out.println("NOTA FINAL = " + resultado);
}

sc.close();

I get exception error message after I tried to input:"45.5" on line 19 (nota1 = sc.nextDouble();).

Error message:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at application.Program.main(Program.java:19)


Solution

  • You just need to change the order of your first to lines to

    Locale.setDefault(Locale.US);
    Scanner sc = new Scanner(System.in);
    

    To first set the system default locale before you create your Scanner. When creating a new Scanner it will get and use the default locale that is set at the moment of its creation, therefor setting the default locale must be done before the Scanner initialization.

    Alternatively you could also use:

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

    to dreictly set a locale to use on the scaner without modifying the default locale.