1

For the program, if the user enters anything other than a number that's 0 or higher then the program would say "Invalid. Enter a number that's 0 or higher." The program would then continue to say "Invalid. Enter a number that's 0 or higher." again and again until a number of 0 or higher is entered.

The problem is that if I enter a letter the program does not respond with "Invalid. Enter a number that's 0 or higher."

This is all I can do so far:

    class Program
    {
        static void Main(string[] args)
        {
            string numberIn;
            int numberOut;

            numberIn = Console.ReadLine();

            if (int.TryParse(numberIn, out numberOut))
            {
                if (numberOut < 0)
                {
                    Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
                Console.ReadLine();
                }
            }           
        }
    }
4

3 回答 3

3

你需要某种循环。也许是一个while循环:

static void Main(string[] args)
{
    string numberIn;
    int numberOut;

    while (true) 
    {
        numberIn = Console.ReadLine();

        if (int.TryParse(numberIn, out numberOut))
        {
            if (numberOut < 0)
            {
                Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
            }
            else
            {
                break; // if not less than 0.. break out of the loop.
            }
        }    
    }

    Console.WriteLine("Success! Press any key to exit");
    Console.Read();
}
于 2013-10-04T00:24:03.550 回答
2

将您的 if 替换为:

while (!int.TryParse(numberIn, out numberOut) || numberOut < 0)
{
    Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
    numberIn = Console.ReadLine();
} 
于 2013-10-04T00:23:56.387 回答
0

如果你想要一个简单、整洁的方法,你可以使用这个:

while (Convert.ToInt32(Console.ReadLine()) < 0)
{
    Console.WriteLine("Invalid entry");
}

//Execute code if entry is correct here.

每次用户输入一个数字,它都会检查输入的数字是否小于0。如果输入无效,则while循环继续循环。如果输入有效,则条件为假,循环关闭。

于 2013-10-04T00:32:09.820 回答