Problem
I was messing around with Java today, and bumped into something that I can't fix by myself. I'm trying to get a double value from scanner but always get this error:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Main.main(Main.java:20)
Source code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final char ADD = '+';
final char SUBTRACT = '-';
final char MULTIPLY = '*';
final char DIVIDE = '/';
double num1;
double num2;
char operator;
Scanner sc = new Scanner(System.in);
num1 = sc.nextDouble();
num2 = sc.nextDouble();
operator = sc.next().charAt(0);
System.out.print(num1 + " " + operator + " " + num2 + " = ");
switch (operator) {
case ADD:
System.out.print(num1 + num2);
break;
case SUBTRACT:
System.out.print(num1 - num2);
break;
case MULTIPLY:
System.out.print(num1 * num2);
break;
case DIVIDE:
System.out.print(num1 / num2);
break;
default:
System.out.println("Error");
break;
}
}
}
My input:
5.2
And then the exception is thrown.
I also have a small video illustrating the problem: https://streamable.com/wes4g1
Minimal example
I was even able to reproduce the issue with a very minimal setup like:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double value = scanner.nextDouble();
System.out.println(value);
}
}
with the input 5.2
or any other decimal.
Inputing an actual integer value, for example just 5
works however.