java 当我输入双精度值时,nextDouble() 抛出 InputMismatchException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5929120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nextDouble() throws an InputMismatchException when I enter a double
提问by Helgi
import java.util.*;
class Averager
{
public static double unlimited()
{
int count = 0;
double sum = 0;
Scanner scan = new Scanner(System.in);
while(scan.hasNext())
{
double d = scan.nextDouble();
sum += d;
count++;
}
double ave = sum/count;
return ave;
}
public static void main(String[] args) {
System.out.println(unlimited()+"\n");
}
}
There is no error when I use integers but if I use numbers with point in it a error appears.
使用整数时没有错误,但如果使用带点的数字,则会出现错误。
$ javac Averager.java; java Averager
0.5
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextDouble(Scanner.java:2387)
at Averager.unlimited(Averager.java:12)
at Averager.main(Averager.java:21)
To my best understanding 0.5 should be covered by double. If not please can someone correct me.
据我所知,0.5 应该被双倍覆盖。如果没有,请有人纠正我。
回答by Kaj
It might be locale dependent. Decimal numbers are e.g written as 0,5 in Sweden.
它可能取决于语言环境。十进制数字例如在瑞典写为 0,5。
Change your code so that it says e.g.:
更改您的代码,使其显示例如:
Scanner scan = new Scanner(System.in);
scan.useLocale(Locale.US);
回答by Chelton
This worked for me, changing the locale did not.
Scanner sc = new Scanner(System.in);
// val = sc.nextDouble(); - crashes with java.util.NoSuchElementException
// If Java crashes with legal Java code, wrap the call in a hasNextLine() test
if (sc.hasNextLine())
{
val = sc.nextDouble();
}