Good morning everyone... I am wondering where to put the try-catch block for not integer Input(InputMismatchException) to work in this code, If I put it here doesn't work, if I put it before while, it's an infinite loop, if you can explain where and why it will be perfect, thank you for your time.
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!");
}
}
}
There are may ways to go about this. Always strive for solutions that make your code easier to read and understand.
One way to do that: you could for example create another helper method fetchSelectionFromUser() that does one thing only: loop (with try catch) until the user entered a valid number.
One guiding rule is the single layer of abstraction principle. And that tells you that having a-switch-in-a-try-in-a-loop isn't the way to go. As said, you could go for a loop that simply calls two methods: one that fetches the input, and another one that processes it.