Home > OS >  Validating Input string with Exceptions in Java
Validating Input string with Exceptions in Java

Time:08-25

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);

CodePudding user response:

I want to throw, catch and handle exception if user enters value other than "A","B" or "C"

This can be coded in different ways, and this syntax is useful in case you have more values to compare:

// Using Java 8 Streams
if (Stream.of("A", "B", "C").noneMatch(e -> e == t)) { ...
// Using Java 7 Collections
if (! Arrays.asList("A", "B", "C").contains(t)) { ...
// Using Java 9 Collections
if (! List.of("A", "B", "C").contains(t)) { ...

CodePudding user response:

Your problem is if condition, when you enter A, the first condition will be false, but second condition will be true, because t equals to A not B therefore second condition will be true, if one of the conditions is true, whole if condition will be true because this is OR statement. Therefore, if block will be executed.

try to change it to the following (AND statement)

if(!t.equals("A") && !t.equals("B") && !t.equals("C"))
  • Related