java - 扫描仪双值 - InputMismatchException

标签 java inputmismatchexception

我尝试以最简单的方式使用扫描仪:

代码:

double gas, efficiency, distance, cost;
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of gallons of gas in the tank: ");
gas = scanner.nextDouble();
System.out.print("Enter the fuel efficiency: ");
efficiency = scanner.nextDouble();

但是在第一次输入 5.1 之后它会抛出:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextDouble(Scanner.java:2456)
    at udacity.MileagePrinter.main(MileagePrinter.java:59)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

JavaDocs 状态:

Thrown by a Scanner to indicate that the token retrieved does not match the
pattern for the expected type, or that the token is out of range for the expected type.

但在我看来,一切看起来都正确,应该可以正常工作。

问题:

  • 为什么会在这种情况下发生这种情况?
  • 如何规避这个麻烦?

最佳答案

您应该为您的扫描仪精确设置区域设置。

Scanner scanner = new Scanner(System.in).useLocale(Locale.US);

来自 doc :

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() method; it may be changed via the useLocale(java.util.Locale) method

The localized formats are defined in terms of the following parameters, which for a particular locale are taken from that locale's DecimalFormat object, df, and its and DecimalFormatSymbols object, dfs.

因此,您的默认语言环境肯定使用 DecimalFormat,它期望逗号作为小数分隔符而不是点。

关于java - 扫描仪双值 - InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17150627/

相关文章:

java - 贾斯珀报告 : How to combine two report streams into one PDF output?

java - 为什么构建失败并显示 JRadioButton[] 数组中的空值

Java InputMismatchException 与 Scanner 循环

在输入中使用空格时 Java 扫描器输入不匹配

java - 读取 boolean 值时发生 InputMismatch 异常

java - Eclipse 中有用于将标签应用于文件的插件吗?

java - 能否将 Java Swing 桌面应用程序转换为 UWP 百年纪念应用程序 (AppX)?

java - 为什么当我使用扫描仪 sc.nextDouble() 时出现 InputMismatchException

Java 输入不匹配异常?

java - 对子类实例使用父类(super class)类型