[英]How to restrict user input?
我想限制用户输入,因此他只能输入28、29、30或31。
我知道有一种方法可以通过检查输入是否在有效日期/天的数组中来实现。 有人可以解释一下我该怎么做吗? 例如,如果
int []天=新的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;
}
谢谢
如果尝试检查输入是否在有效输入的数组中,则可以使用.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`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.