防止用户提交超出范围的值
c#
我的 C# 程序中有这段代码(目前是为 25 - 30 岁的成年人设计的)
Console.Write("Please enter in your age in the range of 25 - 30 years old: ");
string age = Console.ReadLine();
当提示用户时,我希望他们只输入值 25、26、27、28、29 或 30
我不希望用户输入范围之外的数字。
有没有办法防止这种情况发生,以便当用户输入超出范围的值时,将显示一条消息,说明用户输入了不合适的数字?
回答
Andrei 的回答很好,但是我建议使用int.TryParse,因为您的用户可能会输入愚蠢的值,否则会导致您的程序崩溃(例如:使用非数字字符):
Console.Write("Please enter in your age in the range of 25 - 30 years old: ");
int age;
while (true)
{
string strAge = Console.ReadLine();
// checks input validity (integer and within [25-30] range)
if (int.TryParse(strAge, out age) && age >= 25 && age <= 30)
{
Console.WriteLine("Welcome");
// ... and we leave the loop
break;
}
else
{
Console.WriteLine("Wrong input, please try again");
// ... and we go back to ReadLine
}
}
奖励:以上代码使用循环,因此您的用户可以继续输入值,直到他们最终满足条件