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();
返回"牛肉",将"Taco"留在流中。然后,您的下一个sc.nextInt();
返回"Taco",它不是整数,并导致一个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();
您似乎正在尝试将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 将捕获此异常并告诉用户他们做错了什么。