0

After a long and painful debugging session I found a peculiar behaviour of Scanner. The Scanner is initialized with input is on the format:

1.0,2.0,5.0,10

And as such a mix of integers and doubles. But, when running the following loop:

scan.useDelimiter("[, ]");
while(scan.hasNext()) {
    if(scan.hasNextDouble()) {
        System.out.println(scan.nextDouble());
    } else {
        System.out.println("Other:"+scan.next());
    }
}

I get the output:

Other:1.0
Other:2.0
Other:5.0
10.0

Which is weird. It interprets integers as doubles (as expected) but can not recognize "true" doubles. However, if I change the first line to:

scan.useDelimiter("[. ]");

It returns:

1.0
0.2
0.5
0.1

Which means Scanner.hasNextDouble recognizes "0,2" as a double but not "1.0". Is this by design? Seems very counterintuitive to me. Happy for any help I can get.

  • 1
    Some countries use a comma as a [decimal separator](https://en.wikipedia.org/wiki/Decimal_separator). You most likely have a default Locale of one of these countries. See also https://stackoverflow.com/questions/15643829/how-exactly-does-java-scanner-parse-double – Michael Apr 04 '18 at 14:17

1 Answers1

0

Found an answer on this link: https://stackoverflow.com/a/40028178/7546831

Apparently a locale issue, in some regions doubles are written as "1,0" and not "1.0" according to Java. It is however possible to specify which you prefer. The more you know!