Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InputMismatchException using Scanner#nextDouble with valid values

Tags:

java

Here is my code for my scanner:

import java.util.Scanner;
public class TryDouble {

    public static void main(String  [] args){
        Scanner jin = new Scanner(System.in);
        double a = jin.nextDouble();
        double b = jin.nextDouble();
        double c = jin.nextDouble();
        System.out.println(a + b + c);
    }
}

For input: 0.2 0.5 0.9, I got:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at TryDouble.main(TryDouble.java:6)

What can I do to remove that error?

like image 904
Stefanija Avatar asked Dec 11 '15 14:12

Stefanija


1 Answers

It's a locale issue : If you want to use . you can try something like :

package test;

import java.util.Locale;
import java.util.Scanner;
public class TryDouble {

    public static void main(String  [] args){
        Scanner jin = new Scanner(System.in).useLocale(Locale.US); 
        double a = jin.nextDouble();
        double b = jin.nextDouble();
        double c = jin.nextDouble();
        System.out.println(a + b + c);
    }
}
like image 174
alias_boubou Avatar answered Nov 14 '22 22:11

alias_boubou