java - 线程“main”中的异常 java.util.InputMismatchException ,扫描仪出错
问题描述
在练习 Java 时,我被错误困住了好几个小时。当我输入带小数点的价格时,出现此错误
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at grocerystore.GroceryStore.main(GroceryStore.java:19)
C:\Users\aslan\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
我的代码:
package grocerystore;
import java.util.Scanner;
/**
*
* @author aslan
*/
public class GroceryStore {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
double [] prices = new double [5];
Scanner in = new Scanner(System.in);
System.out.println("Enter 5 prices: ");
prices[0] = in.nextDouble();
prices[1] = in.nextDouble();
prices[2] = in.nextDouble();
prices[3] = in.nextDouble();
prices[4] = in.nextDouble();
double total = prices[0] + prices[1] + prices[2] + prices[4];
System.out.printf("the tot1al of all 5 items is:$%5.2f" +total);
}
}
有人可以帮忙吗???
解决方案
除了数字或句号之外的任何内容in.nextDouble()
都会抛出InputMismatchException
. 所以尽量确保你只输入数字和句号。
此外,printf()
的参数是格式字符串,然后是参数。由于您提供的格式说明符中有一个格式说明符String
,因此它必须有一个要匹配的参数。所以正确的语法是
.out.printf("the tot1al of all 5 items is:$%5.2f", total);
另外,我注意到您错过了prices[3]
. 一个可行的解决方案:
double[] prices = new double[5];
Scanner in = new Scanner(System.in);
System.out.println("Enter 5 prices: ");
prices[0] = in.nextDouble();
prices[1] = in.nextDouble();
prices[2] = in.nextDouble();
prices[3] = in.nextDouble();
prices[4] = in.nextDouble();
double total = prices[0] + prices[1] + prices[2] + prices[3] + prices[4];
System.out.printf("the tot1al of all 5 items is:$%5.2f", total);
Output:
Enter 5 prices:
.0
.1
.2
.3
.4
the tot1al of all 5 items is:$ 1.00
推荐阅读
- linux - Visual Studio linux项目的boost链接错误
- c - C中字符串中的MD5散列
- javascript - 重现相同的行为
- asciidoctor - 为什么片段包含 spring-restdocs-asciidoctor 的错误?
- bash - 从位于其他服务器上的 CLI 程序获取数据的正确方法是什么?
- python - 使用 python3 打印字符串格式:如何从数组打印?
- varnish-vcl - varnish配置后端主机域名还是localhost?
- ios - CAShapeLayer的定位
- python - 我的代码有一个错误,缩进中的制表符和空格不一致尝试了一些修复,但没有任何效果
- google-app-engine - GCloud AppEngine 无法 ssh 进入标准实例