Reputation: 39
I'm trying to make it so that when a number is entered my program will not crash, which this does so far. Then I want it to re ask for an input until the correct charcter type is enetered.
int firstNum;
int Operation = 0;
switch(Operation)
{
case 1:
bool firstNumBool = int.TryParse(Console.ReadLine(), out firstNum);
break;
}
Upvotes: 0
Views: 129
Reputation: 186843
Decompose your solution; extract a method for inputing an integer:
private static int ReadInteger(string title) {
// Keep on asking until correct input is provided
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, not a valid integer value; please, try again.");
}
}
And then use it:
int firstNum;
...
switch(Operation)
{
case 1:
firstNum = ReadInteger("First number");
break;
...
Upvotes: 2