Reputation:
Scanner console = new Scanner(System.in);
//where the menu would be
String menuInput;
//if what user inputs isn't "1", "2" or "3", an error message is shown
do {
menuInput = console.next();
if (!menuInput.equals("1") && !menuInput.equals("2") && !menuInput.equals("3")) {
System.out.println("Enter Valid Input");
}
} while (!menuInput.equals("1") && !menuInput.equals("2") && !menuInput.equals("3"));
I have a menu with 3 options, each option is selected by inputting either "1", "2", or 3", however when any combination of the 3 valid inputs are entered with a space between them e.g. "1 2" it will accept it as a vaild input.
Is there a way to make sure it only accepts one valid input at a time?
Upvotes: 1
Views: 133
Reputation: 121
Your code can be modified to take the whole line of input instead of just the first set of characters.
This line gets the user input from the start of the input buffer till the first space or end-of-line character, whichever is first.
menuInput = console.next()
To get the entire line user the following. It will get the input from the start of the input buffer until the end-of-line character.
menuInput = console.nextLine()
Upvotes: 2
Reputation: 3581
Your problem: console.next()
. This takes the next token from the input - which is space-delimited. So an input of "1 2" doesn't return "1 2" - it returns "1", because it reaches the space and returns everything before it as one token.
If you want to return the whole line, use console.nextLine()
, which will go until the line break (the enter key). This will make your code function as you want.
Upvotes: 1