问题描述
我无法从我的 bash 终端在我的程序中输入双精度值.下面是我用来弄清楚为什么会发生这种情况的代码.
I am unable to enter doubles value in my program from my bash terminal. Below is the code I used to figure out why it is happening.
这是我的测试代码:
import java.util.*;
public class DoubleTest {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
double n = sc.nextDouble();
System.out.println(n);
}
}
使用以下输入 5,我得到了预期的结果.
With the following input 5, I get the expected results.
user $ java DoubleTest
5
5.0
现在是有趣的部分.我输入了一个在代码中声明的 Double,然后发生了这种情况:
Now to the interesting part. I input a Double as declared in the code, and this happens:
user $ java DoubleTest
5.0
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at DoubleTest.main(DoubleTest.java:6)
当值为 5,0 时 - 结果如下:
And when giving a value of 5,0 - this is the result:
user $ java DoubleTest
5,0
5.0
所以看起来 .
(点)不起作用,而是 ,
(逗号)起作用.
So it seems that the .
(dot) is not working, but instead ,
(comma) is.
我已经检查了我的语言环境,但这应该不是问题.
I already checked my locale, but that shouldn't be the problem.
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
推荐答案
您的 Scanner
可能正在使用 Denmark
Locale
因为它使用 ,
格式化双变量而不是美国默认的 .
.
Your Scanner
is probably using the Denmark
Locale
as it uses ,
to format double variables instead of US default .
.
您可以通过以下方式检查它(我尝试在本地强制我的扫描仪使用丹麦语言环境,它的行为方式与您的实验中相同):
Here is how you can check it (I tried locally forcing my Scanner to use Denmark Locale and it behaves the same way as in your experiments):
Scanner sc = new Scanner(System.in);
System.out.println(sc.locale().getDisplayCountry());
如果是这种情况,您需要将其设置为使用美国 Locale
或任何其他您想要的:
If this is your case, you need to set it to use the US Locale
or any other you want:
Scanner sc = new Scanner(System.in);
sc.useLocale(Locale.US);
System.out.println(sc.locale().getDisplayCountry());
或者,如果您需要同时接受 、
和 .
,您可以简单地使用格式化程序.下面是一个使用 France
作为 Locale 的 NumberFormat
示例,它正确地格式化了 、
和 .
:
Alternatively, if you need to accept both ,
and .
you could simply use a formatter. Here is one example with NumberFormat
using France
as Locale, which formats correctly both ,
and .
:
NumberFormat numberFormat = NumberFormat.getInstance(Locale.FRANCE);
double doubleComma = numberFormat.parse("5,0").doubleValue();
double doubleDot = numberFormat.parse("5.0").doubleValue();
在您的代码中,您将执行以下操作:
In your code you would do something like:
public static void main (String[] args) {
try{
Scanner sc = new Scanner(System.in);
NumberFormat numberFormat = NumberFormat.getInstance(Locale.FRANCE);
double n = numberFormat.parse(sc.next()).doubleValue();
System.out.println(n);
} catch (ParseException e) {
e.printStackTrace();
}
}
这篇关于双接受逗号而不是点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!