I'm using a Windows 7 machine whose "Control Panel\Clock, Language, and Region" is "Denmark"
According to the documentation for Scanner:
A scanner's initial locale is the value returned by the Locale.getDefault() method;
But when I run the code:
System.out.println(Locale.getDefault());
Scanner sc = new Scanner("1.0");
sc.nextDouble();
It outputs "en_US" and then throws a java.util.InputMismatchException at sc.nextDouble() . It works when the scanner is initialized with "1,0"
However, if I explicitly set the Locale:
Locale.setDefault(Locale.US);
System.out.println(Locale.getDefault());
Scanner sc = new Scanner("1.0");
sc.nextDouble();
It outputs "en_US" and then parses the double just fine. Am I missing something, or is the documentation for Scanner wrong?
Edit Following the suggestion of @Perception, I looked at sc.locale() in the first example. It prints "da_DK". So why is it not "en_US", when that is what is being returned by the Locale.getDefault() method?
The parseDouble() method of Java Double class is a built in method in Java that returns a new double initialized to the value represented by the specified String, as done by the valueOf method of class Double. Parameters: It accepts a single mandatory parameter s which specifies the string to be parsed.
parseDouble() We can parse String to double using parseDouble() method. String can start with “-” to denote negative number or “+” to denote positive number.
nextDouble() method scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
The nextDouble() method of java. util. Scanner class scans the next token of the input as a Double. If the translation is successful, the scanner advances past the input that matched.
There are two different Locale categories, one for display and one for format. The scanner uses Locale.getDefault(Locale.Category.FORMAT)
but if you call Locale.getDefault()
you get the locale for display. The setLocale(Locale)
method sets both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With