Я кодирую около 2 недель и создал простую логику для проверки целочисленного значения.
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
Вы также можете использовать вышеприведенное в цикле FOR, если предпочитаете, не объявляя действие в качестве третьего параметра цикла, например
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);
}
}
если вам не нужен цикл, просто удалите всю скобку цикла