Java scanner.nextDouble() gives an exception

Viewed 33

I am learning Java and i have met some problems with scanner.nextDouble and I can`t find any response for me.

import java.util.Scanner;

public class Hypotenuse {
public static void main(String[] args){
    double a;
    double b;
    double c;
    Scanner scanner = new Scanner(System.in);
    System.out.println("Type first side: ");
    a = scanner.nextDouble();
    System.out.println("Type second side: ");
    b = scanner.nextDouble();

    c = Math.sqrt((a*a) + (b*b));
    System.out.println("The c side is: " + c);

    scanner.close();


}
}

The problem is when I`m trying to type number with dot like 1.2 for example which is double type. The exception code is:

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:943)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2569)
at Hypotenuse.main(Hypotenuse.java:10)

How do I can fix it ? Thanks for help

1 Answers

It depends on your system. But if you really want to use the dot, you can change the Locale to make a Scanner read dots in this way:

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

For example:

  • Scanner scanner = new Scanner(System.in).useLocale(Local.US); will use the dot
  • Scanner scanner = new Scanner(System.in).useLocale(Local.ITALY); will use the comma.
Related