多个条件同时tryParse
Multiple conditions in a while 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");
}
}
如果重复输入不正确的值,这是让两个值循环的唯一方法。
如何使用多个值来使用单个循环?
您可以在一个循环中组合 条件:
// 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
我希望能够阻止人们输入除 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");
}
}
如果重复输入不正确的值,这是让两个值循环的唯一方法。
如何使用多个值来使用单个循环?
您可以在一个循环中组合 条件:
// 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