The reason between this is just between using 1.1
or 1,1
in different zones.
The way the Scanner reads the nextDouble
is related to your Locale or Zone setting (which, if not overrided, are loaded from system).
For example, I'm in Poland and my delimiter for decimal or floating point numbers is ,
and regardless the Java standard syntax is to use dot(.
), if I input some number with .
I'll also get InputMismatchException
, but when I use ,
, e.g. 0,6
it finishes flawlessly.
In the same time, regardless of the Zone or Locale, the valueOf
or parseDouble
methods from Double class are using .
as floating point separator.
Scanner class methods starting with next...
are based on the built-in patterns for discovering the proper values. The discovery pattern is build with the common/regular way of writing numbers/values (of the specified type) in your country/zone.
This is very similar to the Data
types, which differs even more on their zone of use.
One of the ways of handling InputMismatchException
here is to catch this exception and require the user to provide the number again, similarly to this question.
Your case is a bit different from the input of natural number (because 1.1
and 1,1
should indicate the floating point number.
The simplest way of handling those two separators for decimal numbers would be to read the input as String, replace the wrong separator and parse to double, like:
static double getDouble(String doubleS) {
doubleS = doubleS.replace(',', '.');
try {
return Double.parseDouble(doubleS);
} catch (NumberFormatException e) {
e.printStackTrace();
throw e;
}
}
Thanks to @Andreas comment, the most appropiate way of handling this would to require the user to provide a decimal number with .
separator, because the printed message (before input) has the separator in its numbers.
This could be done with setting the type of Scanner object locale before number input like:
Scanner keyboard = new Scanner(System.in);
keyboard.useLocale(Locale.US); //this sets the locale which has below separator
System.out.println("Enter a number between 0.0 and 1.0.");