-2

There is an error when I enter the double next value with a point like (1.5) I don't know why?

Even when I put (1,5) with the comma, the same result is wrong.

Can anyone help me fix it?

import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {

    Scanner scan = new Scanner (System.in);

    double inch;

    System.out.println("write the distance in inch:");
    inch = scan.nextDouble();

    System.out.println("the result is " + inch * 2.54 + " cm");
}
}

the output:

write the distance in inch:
1.5
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 ex1.main(ex1.java:10)

Process finished with exit code 1

1 Answers1

0

It looks like your computer is set to use the Arabic Decimal Separator. If you use that instead of a period (.) or comma (,), your program should work.

If you want users to be able to use a period as a decimal separator, you can add scan.useLocale(Locale.US); just after opening the Scanner

 import java.text.DecimalFormatSymbols;
 import java.util.Locale;                      
 import java.util.Scanner;

 public class ex1 {

 public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      scan.useLocale(Locale.US);              // **** new line ****
   
      double inch;

      System.out.print("write the distance in inch: ");
      inch = scan.nextDouble();

      System.out.println("the result is " + inch * 2.54 + " cm");
   }
}

See How to input period as decimal point?

You could stick with the Arabic Decimal Separator. If you want to change it, you don't have to use Locale.US. You could use a different locale that uses a period. Or, a locale that uses a comma. Or, some other character.

Adding that line will affect only that Scanner Object. You can change it for one program by using command line options, or by adding Locale.setDefault(new Locale(~~~~)); (You have to substitute valid language, language and country, or language, country, and variant for ~~~~. You can change it for your Java installation. You can change it system wide. See How do I set the default locale in the JVM? .

Old Dog Programmer
  • 901
  • 1
  • 7
  • 9