Use
int.TryParse[
^] to attempt to convert the user's input to a number.
Use the OR operator (
||
) to test whether the number is outside of the range. It can't be both
"less than or equal to 20" and
"greater than or equal to 50" at the same time!
Add a loop to re-prompt the user until you get a valid number.
int number;
bool isValid = false;
while (!isValid)
{
Console.WriteLine("Enter the integer value only");
string input = Console.ReadLine();
if (!int.TryParse(input, out number))
{
Console.WriteLine("The string '{0}' is not an integer.", input);
}
else if (number <= 20 || number >= 50)
{
Console.WriteLine("Please enter the number between 20 to 50");
}
else
{
isValid = true;
}
}
Console.WriteLine("You entered {0}.", number);