I am following a c# course and trying to upgrade my user input method to check if the entered console input is an integer. I have written myself into a do while loop that I know doesn't work, but I am struggling a bit with coming up with a method that can both check for value and if the entered variable is an integer.
So what I tried here was to do-while until the user entered input is an Integer and between the min and max values. But I get stuck on result is only set to a value in the 'if' block, not the 'else' block. It won't compile unless result is set to something, unassigned variable. And I understand why, because there is a branch where I end up with a variable without value, and that won't pass in my while greater-less comparisson. You can only compare numbers, not nulls or strings.
Should I abandon the do-while loop for something more clever? Right now my 'hack' is to set result = 0 in the case that TryParse is false. That is only useful as long as the user does not need to input 0, in which case the whole thing makes no sense any longer.
static int readInt(string prompt, int low, int high) // METHOD readInt
{
int result;
bool succes;
do
{
int temp;
string intString = readString(prompt);
succes = Int32.TryParse(intString, out temp);
if (succes)
{ Console.WriteLine("The string was a number within the limits, {0}.", intString);
result = int.Parse(intString);
}
else
{
Console.WriteLine("{0} is not a valid number between {1} and {2}", intString, low, high);
result = 0;
}
} while (!succes && (result < low) || (result > high));
return result;
}