Skip to main content
6 of 7
quoted original code, it is mainly for reference
Malachi
  • 29.1k
  • 11
  • 87
  • 188

Ensuring user input is an integer in a range

I have isolated a little bit of code that was causing a small debate between myself and another user. I have taken some of the things that he said and meshed it with the code that was being reviewed in the first place here.

Original Code

while (!validInput) { var playerChoice = -1; Console.WriteLine("Please choose your Gesture "); gameSetup(listOfGestures); try { playerChoice = Convert.ToInt32 (Console.ReadLine()); } catch (FormatException e) { validInput = false; } if (playerChoice > 0 && playerChoice <= listOfGestures.Count) { playerGesture = listOfGestures[playerChoice - 1]; validInput = true; } else { validInput = false; } } 

Here is what I came up with based on our conversation.

New Code

var validInput = false; //forgot this part while (!validInput) { var playerChoice = -1; Console.WriteLine("Please choose your Gesture "); gameSetup(listOfGestures); validInput = int.TryParse(Console.ReadLine(),out playerChoice); if (playerChoice > 0 && playerChoice <= listOfGestures.Count) { playerGesture = listOfGestures[playerChoice - 1]; validInput = true; } } 

Do I need to create a new method to sort out user input and whether or not it is an integer inside the min and max bounds?

Malachi
  • 29.1k
  • 11
  • 87
  • 188