如何限制用户输入?

时间:2016-12-05 20:58:44

标签: c#

我想限制用户输入,因此他只能输入28,29,30或31。

我知道有一种方法可以通过检查输入是否在有效日期/日的数组中来实现。有人可以解释我怎么做检查?例如,如果

int [] days = new int [4] {28,29,30,31};

如何进行验证,检查输入的用户是否在数组内?我应该设置什么条件?我没有要显示的代码,因为我不知道如何编写这种类型的验证。如果无法做到这一点怎么能用if语句来限制用户只限制这4个数字?

到目前为止,我的代码看起来像这样:

    int GetDaysInMonth()
    {
        const int MinDaysInMonth = 28;
        const int MaxDaysInMonth = 31;

        Console.WriteLine("How many days there are in your chosen month? [it needs to be 28, 30 or 31]");
        userInput = Console.ReadLine();

        while (!int.TryParse(userInput, out daysInMonth) || daysInMonth > MaxDaysInMonth || daysInMonth < MinDaysInMonth)
        {
            Console.WriteLine("Wrong input! Remember it needs to be 28, 30 or 31");
            userInput = Console.ReadLine();
        }
        Console.WriteLine();
        return daysInMonth;
    }

由于

1 个答案:

答案 0 :(得分:2)

如果您尝试检查输入是否在有效输入数组中,则可以使用.Contains()方法。

public static bool IsValid(int input, int[] validInputs)
{
    return validInputs.Contains(input);
}

你可以像下面这样使用它:

int input = 28;
int[] validInputs = new[] { 28, 29, 30, 31 };

bool result = IsValid(input, validInputs); //result is `true`