捕获1-100之间的整数

时间:2016-03-24 01:12:53

标签: c# console

我试图在C#中捕获1到100之间的数字,我想循环用户,直到他们输入正确的结果。我有以下内容,但它没有像我期望的那样进行评估,我的知识差距在哪里?

var input=0;

Console.Write("Enter a number between 1 and 100: ");

while (!int.TryParse(Console.ReadLine(), out input) && input>0 && input <=100)
{
    Console.Write("The value must be a number greater than 0, but less than 100 please try again: ");
}

2 个答案:

答案 0 :(得分:2)

您似乎缺少一对括号,!int.TryParse(Console.ReadLine(), out input)被评估,如果用户输入任何内容,则为false。

尝试:

var input=0;

Console.Write("Enter a number between 1 and 100: ");

while (!(int.TryParse(Console.ReadLine(), out input) && input>0 && input <=100))
{
    Console.Write("The value must be a number greater than 0, but less than 100 please try again: ");
}

答案 1 :(得分:0)

 static void Main(string[] args)
    {
        var input = 0;
        Console.Write("Enter a number between 1 and 100: ");
        while (true)
        {
          if (int.TryParse(Console.ReadLine(), out input) && (input < 0 || input > 100))
            {
                Console.Write("The value must be a number greater than 0, but less than 100 please try again: ");
            }
            else
            {
                Console.WriteLine("Thank you for the correct input");
                break;
            }
        }
        Console.ReadKey();        

    }