【问题标题】:Multiple conditions in a while tryParse一段时间内有多个条件 tryParse
【发布时间】:2017-05-07 10:44:41
【问题描述】:

我希望能够阻止人们输入除 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");

            }
        } 

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

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

【问题讨论】:

  • while (!(int.TryParse(Console.ReadLine(), out quant)) || quant &gt; 19 || quant &lt; 0)?
  • 我试过了,除非我输入错误,否则它不会起作用。

标签: c# console tryparse


【解决方案1】:

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

// 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

【讨论】:

  • 你好。是的,我知道我可以将它们结合起来,但它对我不起作用(这就是为什么我留下了我发布的那个烂摊子!)。我会试试你的代码。我一定是在什么地方打错了!
  • @Matt:请您在“它对我不起作用”中更具体一点 - 简单的条件组合有什么问题?
  • 好的,我试过你的代码,它可以工作。也许是因为我使用的是 OR 而不是 AND?不管怎样,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
  • 2021-02-13
  • 2011-10-02
相关资源
最近更新 更多