阻止用户提交超出范围的值

  • 本文关键字:范围 用户 提交 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
}
}

奖金:上面的代码使用了一个循环,这样用户就可以一直输入值,直到最终满足

条件

最简单的方法是使用if语句。但是您需要首先使用convert将您的年龄转换为int型。ToInt32或int。解析

Console.Write("Please enter in your age in the range of 25 - 30 years old: ");
int age = int.Parse(Console.ReadLine());
if(age <= 30 && age >= 25)
{
Console.WriteLine("Welcome");
}
else
{
Console.WriteLine("Your age is not valid!");
}

相关内容

最新更新