首页 > 解决方案 > 防止用户提交超出范围的值

问题描述

我的 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

我不希望用户输入超出范围的数字。

有没有办法可以防止这种情况发生,这样当用户输入超出范围的值时,会显示一条消息,说明用户输入了不正确的数字?

标签: c#

解决方案


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
    }
}

奖励:上面的代码使用循环,因此您的用户可以继续输入值,直到他们最终满足条件


推荐阅读