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

How to validate user input in Java?

I’m trying to get user input and check if it is "1" or "2" and display an error messages if it’s not. I keep getting error messages even when the input is correct.

Scanner user_input = new Scanner(System.in);
String choice = "";
// Input Validation
do {
   // Read user choice
   choice = user_input.nextLine();
            
   if (!choice.equals("1") || !choice.equals("2"))
      System.out.println("Invalid input. Give new value");
   }while (!choice.equals("1") || !choice.equals("2"));```

>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 condition is incorrect.
Use logical AND if need to eliminate both 1 and 2.
I think you wanted to achieve this

       do {
            choice = user_input.nextLine();

            if (!choice.equals("1") && !choice.equals("2"))
                System.out.println("Invalid input. Give new value");
        } while (!choice.equals("1") && !choice.equals("2"));

Also to remove redundancy and improve the readability of code consider removing the validation logic to a separate method.

public static void main(String[] args) {
        Scanner user_input = new Scanner(System.in);
        String choice = "";
        
        do {
            choice = user_input.nextLine();

            if (!choice.equals("1") && !choice.equals("2"))
                System.out.println("Invalid input. Give new value");
        } while (isValid(choice));

        System.out.println("Your input is valid: " + choice);
    }
    
    private static boolean isValid(String choice) {
        return !choice.equals("1") && !choice.equals("2");
    }
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