Search code examples
javadoublejava.util.scannermismatch

How come user input doubles do not accept the same parameters as a regular double?


I'm currently a beginner when it comes to Java, and I stumbled onto something that has startled me a little bit.

Using the scanner, I tried to create a program that allowed me to compare 2 numbers. As in:

num1 > num2
num2 < num1
num1 == num2

And such.

I intended to use doubles because it allows a wide variety of numbers, ranging from whole numbers to decimals. The issue was that whenever I was to enter a number to the console when it asked me; if the number had a full stop it'd give me a mismatch exception error. I tried overcoming this problem by implementing a scanner.nextLine(); or a (double) before the nextDouble(); method. But that did not work. Could someone give me a hand? I'll try to explain it further if my explanation of the problem was not good enough, this is the first time I use this website.

public static void numeralComparison() {
    Scanner scanner = new Scanner(System.in);

    System.out.println("Input the first number. Use a comma to indicate decimal points: ");
    double num1 = (double) scanner.nextDouble();
    scanner.nextLine();

    System.out.println("Input the second number: ");
    double num2 = (double) scanner.nextDouble();
    scanner.nextLine();

    if(num1 < num2) {
        System.out.println(num1 + " < " + num2);
    } else if (num2 < num1) {
        System.out.println(num2 + " < " + num1);
    } else {
        System.out.println(num1 + " = " + num2);
    }

    scanner.close();

}

If I supplied the console with the number "30,0", it worked. It didn't throw an exception. However, if I were to, for example, supply it with "30.0" it'd throw me an InputMismatch exception.

JDK Specifications: Corretto 11, IntelliJ IDEA


Solution

  • nextDouble respects your locale settings (i.e. which character to use as decimal separator) and defaults to Locale.getDefault. But you can tell the Scanner which Locale to use via useLocale.

    Since it appears that you are looking for English-style decimals, you can set scanner.useLocale(Locale.ENGLISH) before reading input:

    public static void numeralComparison() {
        Scanner scanner = new Scanner(System.in);
        scanner.useLocale(Locale.ENGLISH);
    
        System.out.println("Input the first number. Use a comma to indicate decimal points: ");
        double num1 = (double) scanner.nextDouble();
        scanner.nextLine();
    
        System.out.println("Input the second number: ");
        double num2 = (double) scanner.nextDouble();
        scanner.nextLine();
    
        if (num1 < num2) {
            System.out.println(num1 + " < " + num2);
        } else if (num2 < num1) {
            System.out.println(num2 + " < " + num1);
        } else {
            System.out.println(num1 + " = " + num2);
        }
    
        scanner.close();
    }