简体   繁体   English

如何限制用户输入?

[英]How to restrict user input?

I want to restrict user input, so he can only type in 28,29,30 or 31. 我想限制用户输入,因此他只能输入28、29、30或31。

I know that there is a way to do it by checking if the input is in an array of valid dates/day. 我知道有一种方法可以通过检查输入是否在有效日期/天的数组中来实现。 Could someone explain me how can I do a check? 有人可以解释一下我该怎么做吗? For example if 例如,如果

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

How can I do validation that will check if what user inputted is inside the array? 如何进行验证,以检查用户输入的内容是否在数组中? What conditions should I set? 我应该设定什么条件? I don't have a code to show since I do not know how to write that type of validation. 我没有要显示的代码,因为我不知道如何编写这种类型的验证。 If there is no way to do it how can restrict user with if statement that will restrict him to only these 4 numbers? 如果没有办法,如何用if语句将用户限制在仅这4个数字上?

My code so far looks like that: 到目前为止,我的代码如下所示:

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

Thanks 谢谢

If you are trying to check if an input is in an array of valid inputs you could use the .Contains() method. 如果尝试检查输入是否在有效输入的数组中,则可以使用.Contains()方法。

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

You could use it like below: 您可以像下面这样使用它:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM