扫描仪双值 - InputMismatchException [英] Scanner double value - InputMismatchException

查看:144
本文介绍了扫描仪双值 - InputMismatchException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried use scanner at easiest way:

代码:

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 之后它会抛出:

But after first input 5.1 it throws:

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.

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

But to my mind all look correctly, and should work OK.

问题:


  • 为什么会出现这种情况?

  • 如何规避这个麻烦?

推荐答案

您应该为扫描仪准确一个区域设置。

You should precise a Locale for your Scanner.

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

来自 doc


此类能够扫描
标准格式的数字以及扫描仪的语言环境格式。
扫描程序的初始语言环境是
Locale.getDefault()方法返回的值;它可以通过
useLocale(java.util.Locale)方法更改


本地化格式是根据以下
参数定义的,特定的语言环境取自该语言环境的
DecimalFormat对象,df及其和DecimalFormatSymbols对象,
dfs。

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,它将逗号作为小数分隔符而不是点。

So your default locale use certainly a DecimalFormat that expect a comma as a decimal delimiter instead of a dot.

这篇关于扫描仪双值 - InputMismatchException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆