一段时间的多个条件tryParse

时间:2017-05-07 10:44:41

标签: c# console tryparse

我希望能够阻止人们输入0到19之间的int值以外的任何内容。

使用tryParse,我可以确保只输入整数值。使用标准while循环,我可以确保只能输入0到19之间的整数,但我很难合并为两个值。

到目前为止,我通过分离两个循环使其工作的唯一方法,它看起来很混乱。像这样:

        while (!(int.TryParse(Console.ReadLine(), out quant)))
        {

           Console.Clear();
           Console.WriteLine("Current total: £" + total.ToString("0.00\n"));
           Console.WriteLine("That is an invalid quantity. Please enter the quantity again");

        }

        while ((quant >= 20 || quant < 0))
        {
            Console.Clear();
            Console.WriteLine("Current total: £" + total.ToString("0.00\n"));
            Console.WriteLine("That is an invalid quantity. Please enter the quantity again");


            while (!(int.TryParse(Console.ReadLine(), out quant)))               {


                Console.Clear();
                Console.WriteLine("Current total: £" + total.ToString("0.00\n"));
                Console.WriteLine("That is an invalid quantity. Please enter the quantity again");

            }
        } 

如果重复输入错误值,这是我可以让两个值循环的唯一方法。

如何使用多个值来使用单个循环?

1 个答案:

答案 0 :(得分:3)

您可以在一个循环中组合条件:

// we want: Console.ReadLine() being an integer value (quant) and
//          quant >= 0 and
//          quant <= 19
while (!(int.TryParse(Console.ReadLine(), out quant) && 
         quant >= 0 && 
         quant <= 19)) {
  Console.Clear();

  Console.WriteLine("Current total: £" + total.ToString("0.00\n"));
  Console.WriteLine("That is an invalid quantity. Please enter the quantity again");
}

// quant is integer and within [0..19] range