在 Java 中使用 java.util.Scanner 时出现 InputMismatchException

InputMismatchException when working with java.util.Scanner in Java

我正在尝试创建一种库存存储程序,用户可以在其中输入、删除和搜索商品和价格。但是,当输入值时,我得到一个 InputMismatchException。这是我目前的 WIP 代码:

String item;
        double price;

        while(running == true){

            System.out.println("Enter the item");

            item = input.nextLine();

            System.out.println("Enter the price");

            price = input.nextDouble();

            inv.put(item, price);

           System.out.println(inv);

        }

我注意到,在循环的第二次迭代中,它跳过了字符串输入。这是控制台输出:

Enter the item
box
Enter the price
5.2
{box=5.2}
Enter the item
Enter the price
item
Exception in thread "main" java.util.InputMismatchException

添加 input.nextLine() 如下:

String item;
        double price;

        while(running == true){

            System.out.println("Enter the item");

            item = input.nextLine();

            input.nextLine();

            System.out.println("Enter the price");

            price = input.nextDouble();

            input.nextLine();

            inv.put(item, price);

           System.out.println(inv);

        }

input.nextLine() 将扫描仪带到下一行输入,但 input.nextDouble() 不会。因此,您需要将扫描仪推进到下一行:

            price = input.nextDouble();
            input.nextLine();

或者,您可以直接使用 nextLine() 并将其解析为 Double:

            price = Double.parseDouble(input.nextLine());

有关详细信息,请参阅此问题:Java: .nextLine() and .nextDouble() differences