Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validating Input string with Exceptions in Java

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading