środa, 1 czerwca 2016

InputMismatchException with Scanner double

import java.util.*;

public class Challenge_day1 {
    public static void main(String[] args){

        Scanner scan = new Scanner(System.in);
        System.out.print("enter x: ");
        double x = scan.nextDouble();

        System.out.print("enter y: ");
        double y = scan.nextDouble();

        double suma = (x+y);
        System.out.print(suma);

   }
}


output error:

enter x: 2.2
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 Challenge_day1.main(Challenge_day1.java:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Process finished with exit code 1

how to fix it?

change line Scanner to:
Scanner scan = new Scanner(System.in).useLocale(Locale.US);

it is related to jvm locale configuration -- in my example :
enter x: 2,1
enter y: 3,2

not 2.1 or 3.2




Brak komentarzy:

Prześlij komentarz