我尝试以最简单的方式使用扫描仪:
代码:
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状态:
由 Scanner 抛出以指示检索到的令牌与预期类型的模式不匹配
,或者令牌超出预期类型的范围。
但在我看来,一切看起来都正确,应该可以正常工作。
问题:
- 为什么会在这种情况下发生?
- 如何规避这个麻烦?