首页 > 解决方案 > 线程“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);
    }
}

有人可以帮忙吗???

标签: java

解决方案


除了数字或句号之外的任何内容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

推荐阅读