多输入数据验证

时间:2018-10-21 19:35:55

标签: c# validation console-application

我有多个输入需要验证。例如:

  • 输入实例数:
  • 输入可用的IPv4数量:
  • 输入可用的IPv4数量:
  • 输入可用的IPv6数量:
  • 输入用户数: ...

每个输入都必须大于0。如果输入无效,则提示将继续询问。最佳的执行方式是什么? 我正要为每个变量创建一个布尔变量,并使用while循环将布尔值更改为true,...但这会花费很长时间,因为我有10多个这样的输入。 谢谢,感谢您的帮助

2 个答案:

答案 0 :(得分:1)

听起来像这样

class Program
{
    static void Main(string[] args)
    {
        int instances = CheckValues("Number of instances");
        int numofIpv4 = CheckValues("number of ipv4");
        int numofIpv6 = CheckValues("number of ipv6");
        //etc
    }

    private static int CheckValues(string input)
    {
        int parserValue = 0;
        string enteredValue = string.Empty;
        do
        {
            Console.WriteLine(input);
            enteredValue = Console.ReadLine();
        }
        while (!Int32.TryParse(enteredValue, out parserValue) || parserValue == 0);
        return parserValue;
    }
}

答案 1 :(得分:0)

这是您想要的伪代码简单设计:

IDictionary<string, int> dict = new Dictionary<string, int>(); // where you would store all
                                                               // the answers

String prompt1 = "Enter a number ...";
String prompt2 = "Enter number of IPv4 ..."; // and so on

// initialize your stack
Stack<string> prompts= new Stack<string>();
prompts.Push(prompt1);
prompts.Push(prompt2);

while(prompts.Count != 0){
    String prompt = prompts.Peek(); // this doesn't remove the element from stack
    int input = 0;

    //display prompt to user and get input in input variable

    if(input>0){ // or whatever validation logic you want
        dict.Add(prompt, input);
        prompts.Pop(); //removes topmost element
    }
}