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/59704126/

相关文章:

java - 如何在我的程序中使用 try/catch/finally 过滤扫描仪输入错误?

java - 处理输入扫描器引起的异常

java - 为什么这个 do while 循环无限运行?

具有自动完成和上下文菜单的 Java Swing 组合框

java - 以编程方式设置 FrameView 的大小

java - 首先为什么要有抽象类?

java - try catch 循环(InputMismatchException 和 ArrayIndexOutOfBoundsException 之间的区别)

java - 如何调用 public boolean onPrepareOptionsMenu(Menu menu)

Java 数组自定义函数

java - 在 Java 中使用 java.util.Scanner 时出现 InputMismatchException