At a very simple level, I'd use a do-while
loop, as you want to enter the loop at least once. I'd then determine the validity of the input, using a boolean
flag and make further determinations based on that, for example...
Scanner myScan = new Scanner(System.in);
boolean userInputCorrect = false;
String food = null;
do {
System.out.println("Enter food");
food = myScan.nextLine();
userInputCorrect = food.equalsIgnoreCase("b") || food.equalsIgnoreCase("e") || food.equalsIgnoreCase("exit");
if (!userInputCorrect) {
System.out.println("Error");
}
} while (!userInputCorrect);
System.out.println("You selected " + food);
An expanded solution might use some kind of valid
method, into which I can pass the String
and have it validate the input based on known values, but that's probably a little beyond the scope of the question
As has been, correctly, pointed out but others, it would be more efficient to convert the input to lowercase once and compare all the values, in this case, it might be better to use a switch
statement...
Scanner myScan = new Scanner(System.in);
boolean userInputCorrect = false;
String food = null;
do {
System.out.println("Enter food");
food = myScan.nextLine();
switch (food.toLowerCase()) {
case "b":
case "e":
case "exit":
userInputCorrect = true;
break;
default:
System.out.println("Error");
}
} while (!userInputCorrect);
System.out.println("You selected " + food);
But you could also do...
food = myScan.nextLine().toLowerCase();
userInputCorrect = food.equals("b") || food.equals("e") || food.equals("exit");