为什么我要使用 nextFloat 读取 InputMismatchException?

Why am I getting InputMismatchException to read with nextFloat?

此代码没有语法错误,但是当我输入浮点值时出现 InputMismatchException。 Double 值而不是 float 得到相同的异常。如果我以 F.f 格式(带点)输入每个值,则会出现异常。如果我输入 1,9 值(逗号),则此代码有效。为什么?

Scanner l = new Scanner(System.in);
String n;
int i;
float a;
System.out.print("N: ");
n = l.nextLine();
System.out.print("I: ");
i = l.nextInt();
System.out.print("A: ");
a = l.nextFloat();
System.out.println(n);
System.out.println(i);
System.out.println(a);

提前致谢!

javadoc 解释说 Scanner 方法在读取数字时默认使用默认区域设置的格式设置规则。

它说:

An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault(Locale.Category.FORMAT) method; it may be changed via the useLocale(java.util.Locale) method. The reset() method will reset the value of the scanner's locale to the initial locale regardless of whether it was previously changed.

所以...如果你想让你的程序识别 1.9 而不是 1,9,要么改变你的默认语言环境(在程序中,在启动参数中,或者在系统中设置)...或使用适当的 Locale 配置 Scanner,如所述。