-1

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

  • Hi! (Try) Type with comma! (Depends on your system locale/the "shell" you use.) – xerx593 Sep 12 '22 at 09:13
  • Thanks! But is there a way to change typing from comma to dot? – Błażej Pajor Sep 12 '22 at 09:27
  • 1
    Hello, Please try to find an answer before you ask a question, [Here](https://stackoverflow.com/questions/5929120/nextdouble-throws-an-inputmismatchexception-when-i-enter-a-double) is the same question with possible answers. – George Sep 12 '22 at 09:31

1 Answers1

0

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.
Crih.exe
  • 502
  • 4
  • 16