I\'m trying to implement InputMismatchException to both of my switch (userChoice
ID: 3812720 • Letter: I
Question
I'm trying to implement InputMismatchException to both of my switch (userChoice) statement, but can't figure it out.
public class Driver {
public static void main(String[] args) throws Exception {
new Driver();
}
public Driver() throws Exception {
Scanner input = new Scanner(System.in);
Plant newPlant = new Plant();
ArrayList<Plant> plantPack = new ArrayList<Plant>();
boolean continueInput = false;
do{
try{
System.out.println("Welcome to my PlantPack Interface");
System.out.println("Please select a number from the options below:");
System.out.println("");
while(true) {
System.out.println("1: Add a Plant to the pack.");
System.out.println("2: Remove a Plant from the pack.");
System.out.println("3: Search for a Plant by Name.");
System.out.println("4: Filter PlantPack by Plant Partial Name.");
System.out.println("5: Display Plants in the PlantPack.");
System.out.println("6: Save PlantPack to a File.");
System.out.println("7: Load PlantPack from a File.");
System.out.println("0: Exit the Plant Pack interface.");
int userChoice = input.nextInt();
switch (userChoice) {
case 1:
System.out.println("Enter Plant Type: ");
System.out.println("1: Flower");
System.out.println("2: Fungus");
System.out.println("3: Weed");
try{
int plantType = input.nextInt();
continueInput = false;
switch(plantType) {
case 1:
newPlant = new Flower();
addPlant(plantPack, newPlant);
break;
case 2:
newPlant = new Fungus();
addPlant(plantPack, newPlant);
break;
case 3:
newPlant = new Weed();
addPlant(plantPack, newPlant);
break;
default:
System.out.println("Invalid Input!");
}
} catch (InputMismatchException ex) {
System.out.println("Invalid Input2!");
} while (continueInput);
break;
case 2:
removePlant(plantPack);
break;
case 3:
searchPlant(plantPack);
break;
case 4:
filterPlant(plantPack);
break;
case 5:
displayPlant(plantPack);
break;
case 6:
savePlant(plantPack);
break;
case 7:
loadPlant(plantPack);
break;
case 0:
System.out.println("Thank you for using the Plant Pack Interface. See you again soon!");
System.exit(0);
default:
System.out.println("Invalid Input");
}
}
} catch (InputMismatchException ex) {
System.out.println("Invalid Input2!");
} while (continueInput);
}
Explanation / Answer
InputMismatchException occurs when you try to assign diffrent data type to a variable of different data type.
example
int i="Hello";
so in your case this Exception will occur when you enter different datatype than int while taking input from user.
int userChoice = input.nextInt();
consider below code snippet:
Scanner s=new Scanner(System.in);
try{
int ch=s.nextInt();
}catch(InputMismatchException e){System.out.println("Exception");}
if you enter some string let say "Hello" it will throw an InputMistmatchException and "Exception" will be printed on the console.