I ve been coding for about 2 weeks and created a simple logic to validate an integer has been accepted.
Console.WriteLine("How many numbers do you want to enter?"); // request a number
string input = Console.ReadLine(); // set the input as a string variable
int numberTotal; // declare an int variable
if (!int.TryParse(input, out numberTotal)) // process if input was an invalid number
{
while (numberTotal < 1) // numberTotal is set to 0 by default if no number is entered
{
Console.WriteLine(input + " is an invalid number."); // error message
int.TryParse(Console.ReadLine(), out numberTotal); // allows the user to input another value
}
} // this loop will repeat until numberTotal has an int set to 1 or above
you could also use the above in a FOR loop if you prefer by not declaring an action as the third parameter of the loop, such as
Console.WriteLine("How many numbers do you want to enter?");
string input2 = Console.ReadLine();
if (!int.TryParse(input2, out numberTotal2))
{
for (int numberTotal2 = 0; numberTotal2 < 1;)
{
Console.WriteLine(input2 + " is an invalid number.");
int.TryParse(Console.ReadLine(), out numberTotal2);
}
}
if you don t want a loop, simply remove the entire loop brace