InputMismatchException

InputMismatchException

if (userOption == 2) {
    System.out.println("You have chosen produce! Please enter (1) for organic or (0) for non-organic.");
    type = sc.nextInt();
    System.out.println("Please enter a name for this produce.");
    name = sc.next();
    sc.nextLine();
    System.out.println("Please enter the amount of calories.");
    calories = sc.nextInt();
    System.out.println("Please enter the amount of carbohydrates.");
    carbohydrates = sc.nextInt();

    list.add(new Produce(name, calories, carbohydrates, type));
}


您好,当我在“名称”输入词之间加一个空格时,当我不输入卡路里时,它会给我卡路里的错误InputMismatchError,直到用户都不应该输入卡路里输入一个“名称”。谢谢 :)

最佳答案

您输入的是“牛肉炸玉米饼”,其中包含一个空格。 Java-Doc指出:


扫描器使用定界符模式将其输入分为令牌,
默认情况下,它与空格匹配。


因此,您的sc.next();返回“牛肉”,而在流上保留“塔可”。然后,您的下一个sc.nextInt();返回不是整数的“ Taco”,并导致进入statesInputMismatchException


InputMismatchException-如果下一个标记与Integer正则表达式不匹配或超出范围




要解决此问题,请尝试以下操作:

System.out.println("You have chosen produce! Please enter (1) for organic or (0) for non-organic.");
int type = sc.nextInt();
// Clear the input
sc.nextLine();
System.out.println("Please enter a name for this produce.");
// Read in the whole next line (so nothing is left that can cause an exception)
String name = sc.nextLine();

10-06 08:40