0

I'm using a while loop to validate data ensuring the user enters only a number between 1 and 6. The loop catches the invalid entry no problem, but then when a correct number is entered it needs to be entered a second time in order to proceed. If I take out || menuScan.nextInt() > 6 the loop will work exactly as I need it to but I need to include this line in the loop.

while (!menuScan.hasNextInt() || menuScan.nextInt() > 6) {
    menuScan.nextLine();
    System.err.println("Please enter a valid menu option 1 - 6: "); 
}

menuChoice = menuScan.nextInt();
1
  • I guess will need more context to answer that one... Could you post the rest of your method? Which method triggers the prompt to enter a new value? Commented Dec 22, 2015 at 11:52

1 Answer 1

3

Assign the value to your variable in the moment you read it for the first time:

while (!menuScan.hasNextInt() || (menuChoice = menuScan.nextInt()) > 6) {
    menuScan.nextLine();
    System.err.println("Please enter a valid menu option 1 - 6: "); 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.