【发布时间】:2022-01-13 06:59:12
【问题描述】:
大家早上好...我想知道在此代码中将非整数 Input(InputMismatchException) 的 try-catch 块放在哪里工作, 如果我把它放在这里不起作用,如果我把它放在while之前,它是一个无限循环,如果你能解释它在哪里以及为什么它会完美,谢谢你的时间。
public void additionalIngredients() {
Set<Integer> set = new HashSet<>();
boolean flag = false;
while (!flag) {
System.out.println("Enter your choice for extra toppings ");
int choices = scanner.nextInt();
scanner.nextLine();
try {
switch (choices) {
case 0:
System.out.println("Done");
flag = true;
break;
case 1:
if (!set.contains(choices)) {
double extraSauce = 1.2;
setAdditionalStuff(getAdditionalStuff() + extraSauce);
System.out.println("Extra sauce added on your pizza \n");
break;
} else {
System.out.println("You already added extra sauce, please consider to add something else");
break;
}
case 2:
if (!set.contains(choices)) {
double extraCheese = 2.3;
setAdditionalStuff(getAdditionalStuff() + extraCheese);
System.out.println("Extra cheese added on your pizza \n");
break;
} else {
System.out.println("You already added extra cheese, please consider to add something else");
break;
}
case 3:
if (!set.contains(choices)) {
double largeDough = 0.7;
setAdditionalStuff(getAdditionalStuff() + largeDough);
System.out.println("Your pizza has a large Dough \n");
break;
} else {
System.out.println("Your pizza has already a large dough, consider something else");
break;
}
}
set.add(choices);
} catch (InputMismatchException e) {
System.out.println("Please enter an integer!");
}
}
}
【问题讨论】:
-
你应该在try块
try{ int choices = scanner.nextInt(); ...}中包含从用户那里获取输入 -
仍然是无限循环,我想我必须从一开始就检查我的输入是否为整数,这家伙说的话,使用另一种方法。
-
在 catch 块中包含您的
scanner.nextLine();
标签: java switch-statement try-catch hashset