线程" main"中的例外情况java.util.InputMismatchException,Scanner出错

时间:2018-05-24 18:02:03

标签: java

我在练习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);
    }
}

任何人都可以帮忙???

1 个答案:

答案 0 :(得分:1)

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