Xander Xander - 23 days ago 6
Java Question

parseDouble vs nextDouble

I have the folowing code:

Scanner in = new Scanner(System.in);
while (in.hasNextDouble()) {
System.out.println(Double.parseDouble(in.nextLine()));
}


with input:

1.1
2.2
3.3


Program stops after reading this input whereas, as I assume, it should still read from input.
Why is that?

Answer

The problem could be that your default locale uses comma as delimiter.
Double.parseDouble() - uses always the dot as separator.
in.nextDouble() - uses separator specified by your Locale.
The result is that one of those methods can use comma as separator whereas the other use dot.

To solve that problem, you should unify the method of reading/parsing doubles from your input, and also decide which separator you want to use.
You can set the type of separator, for example by using:
1. Dot delimiter:

Scanner in = new Scanner(System.in);
in.useLocale(Locale.ENGLISH);

or:

Scanner in = new Scanner(System.in);
in.useDelimiter("\\.");

2. Comma delimiter:

Scanner in = new Scanner(System.in);
in.useLocale(Locale.FRENCH);

or

Scanner in = new Scanner(System.in);
in.useDelimiter(",");

So refactoring your code:

Scanner in = new Scanner(System.in);
in.useLocale(Locale.ENGLISH);
while (in.hasNextDouble()) {
    System.out.println(Double.parseDouble(in.nextLine()));
}


To see the problem clearly you can use this code:

Locale.setDefault(Locale.FRANCE);
Scanner in = new Scanner(System.in);
System.out.println(in.hasNextDouble());
Double.parseDouble(in.nextLine());

with input: 1,1

Result of hasNextDouble() is true whereas Double.parseDouble(in.nextLine()) throws NumberFormatException.

Hope it helps.

Comments