当我输入2个单词时,代码不断给出InputMismatchException

时间:2015-12-11 08:40:53

标签: java

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));
}

你好,当我在我的单词之间留一个空格作为" name"的输入时,它给我一个卡路里错误InputMismatchError当我没有加入卡路里,卡路里不是&# 39;甚至应该得到输入,直到用户输入"名称"。谢谢:))

2 个答案:

答案 0 :(得分:1)

您输入的是“Beef Taco”,其中包含一个空格。 Java-Doc州:

  

扫描仪使用分隔符模式将其输入分解为标记,   默认情况下匹配空格。

所以你的sc.next();返回“Beef”,在流上留下“Taco”。您的下一个sc.nextInt();然后返回“Taco”,这不是整数,并导致InputMismatchException states

  

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

要解决此问题,请尝试以下方法:

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();

答案 1 :(得分:0)

您似乎正在尝试将String输入Integer。要捕获它,您可以将代码更改为以下内容:

if (userOption == 2) {
            System.out.println("You have chosen produce! Please enter (1) for organic or (0) for non-organic.");
            try {
                type = sc.nextInt();
            } catch (InputMismatchException e) {
                System.out.println("Wrong format entered.");
                // ask question again or move on.
            }
            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));
    }

try / catch会捕获此异常并告诉用户他们做错了什么。