Фильтр ввода чисел - C#
Формулировка задачи:
Задание:
Проверить попадает ли вводимая переменная в интервал от -10 до 10.Решение:
static void Main(string[] args)
{
const int MIN = -10;
const int MAX = 10;
Console.WriteLine(" Enter a number [-10; 10]: ");
string str = Console.ReadLine();
int Num = Convert.ToInt32(str);
if (Num >= MIN && Num <= MAX)
Console.WriteLine(" OK! The number = {0} [-10; 10]", Num);
else
Console.WriteLine(" ERROR! The number = {0} is out of range");
}Вопрос:
если я ввожу вообще не число, программа падает.Как проверить, вводимая строка вообще число или нет?
Решение задачи: «Фильтр ввода чисел»
textual
Листинг программы
try
{
const int MIN = -10;
const int MAX = 10;
Console.WriteLine(" Enter a number [-10; 10]: ");
string str = Console.ReadLine();
int Num = Convert.ToInt32(str);
if (Num >= MIN && Num <= MAX)
Console.WriteLine(" OK! The number = {0} [-10; 10]", Num);
else
Console.WriteLine(" ERROR! The number = {0} is out of range");
}
catch (FormatException)
{
Console.WriteLine("Введите целое число");
}