Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

java - Scanner double value - InputMismatchException

I tried use scanner at easiest way:

Code:

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();

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)

The JavaDocs state:

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.

Questions:

  • Why this happen at this situation?
  • How to circumvent this trouble?
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should precise a Locale for your Scanner.

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

From the 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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...