I coded the following java snippet. I want to throw, catch and handle exception if user enters value other than "A","B" or "C". I know this can be done without exception but my task is to implement this with exception. The following code catches exception but the problem is that even if I enter value from A,B or C.It still executes the Catch block. Kindly share where i am wrong.
boolean invalid = false;
do {
try {
System.out.println("Enter:");
t = in.nextLine();
invalid=true;
if(!t.equals("A") || !t.equals("B") || !t.equals("C")){
invalid=false;
throw new InputMismatchException("Invalid!");
}
}
catch(InputMismatchException e){
System.out.println("Enter from options.");
invalid = false;
}
}while(!invalid);
if(!t.equals("A") && !t.equals("B") && !t.equals("C")){if (! List.of("A", "B", "C").contains(t)) { ... }- requires Java SE 9. This is useful in case you have more strings to compare.