在java中使用java.util.Scanner时的InputMismatchException
我正在尝试创建一种库存存储程序,用户可以在其中输入、删除和搜索物品和价格。然而,当输入值时,我会得到一个InputMismatchException。以下是我目前掌握的WIP代码:在java中使用java.util.Scanner时的InputMismatchException,java,java.util.scanner,inputmismatchexception,Java,Java.util.scanner,Inputmismatchexception,我正在尝试创建一种库存存储程序,用户可以在其中输入、删除和搜索物品和价格。然而,当输入值时,我会得到一个InputMismatchException。以下是我目前掌握的WIP代码: String item; double price; while(running == true){ System.out.println("Enter the item"); item = input.nextLine();
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()并将其解析为双精度:
price = Double.parseDouble(input.nextLine());
有关更多详细信息,请参见此问题: