How to validate user input in Java? [duplicate]
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"));```
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 (isValid(choice))
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");
}