How exactly does Java Scanner parse double?

余生长醉 提交于 2019-12-01 03:56:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/15643829/how-exactly-does-java-scanner-parse-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!