C# 如何限制用户输入?
我想限制用户输入,所以他只能输入28、29、30或31 我知道有一种方法可以通过检查输入是否在有效日期/天的数组中来实现。有人能告诉我怎么做支票吗?例如,如果 int[]天=新的int[4]{28,29,30,31} 如何进行验证以检查用户输入的内容是否在数组中?我应该设定什么条件?我没有代码可以显示,因为我不知道如何编写这种类型的验证。若并没有办法做到这一点,那个么如何使用If语句来限制用户只使用这4个数字呢 到目前为止,我的代码如下所示:C# 如何限制用户输入?,c#,C#,我想限制用户输入,所以他只能输入28、29、30或31 我知道有一种方法可以通过检查输入是否在有效日期/天的数组中来实现。有人能告诉我怎么做支票吗?例如,如果 int[]天=新的int[4]{28,29,30,31} 如何进行验证以检查用户输入的内容是否在数组中?我应该设定什么条件?我没有代码可以显示,因为我不知道如何编写这种类型的验证。若并没有办法做到这一点,那个么如何使用If语句来限制用户只使用这4个数字呢 到目前为止,我的代码如下所示: int GetDaysInMonth()
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;
}
int GetDaysInMonth()
{
MinDaysInMonth常数=28;
const int MaxDaysInMonth=31;
Console.WriteLine(“您选择的月份有多少天?[需要是28天、30天或31天]”;
userInput=Console.ReadLine();
而(!int.TryParse(用户输入,输出daysInMonth)| | daysInMonth>MaxDaysInMonth | | 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`
您试图限制输入的代码是什么?这是用于控制台应用程序的吗?网络应用?Winforms应用程序?控制台应用程序我已经添加了一段代码,正如我前面解释的那样,我想验证它。看起来不错,你的问题是什么?我的问题是我想验证它,所以它将限制为仅4个数字。28,29,30,31我知道了,谢谢。