检查输入是否存在负整数错误

Checking input for a negative integer error

我正在尝试制作一个程序,该程序将从用户那里获取一个整数并多次抛硬币。但是,当用户输入一个 负整数 时,程序会出现 'overflow Exception.' 我怎样才能让用户只能输入一个正整数?

int newLoop = 0;
        int Number;
        string answer1 = default(string);
        string text = default(string);
        Random newNumber = new Random();
        Console.WriteLine("How many times do you want the coin to flip?\n");
        string line = Console.ReadLine();
        int value;
        if (int.TryParse(line, out value))
        {
            string[] myValues = new string[value];
            while (newLoop < value)
            {
                Number = newNumber.Next(0, 2);
                if (Number == 0)
                {
                    answer1 = "Tails\n";
                    myValues[newLoop] = "Tails";
                }
                else
                {
                    answer1 = "Heads\n";
                    myValues[newLoop] = "Heads";
                }
                text = " " + answer1;
                foreach (char u in text)
                {
                    Console.Write(u);
                }
                newLoop++;
            }
            Console.ReadLine();
            Title();
            Question();
        }
        else if (line == "")
        {
            Console.WriteLine("\nThat is not a valid number...");
            Console.WriteLine("Please try again:");
            Console.WriteLine("~enter to continue~");
            Console.ReadLine();
            coinTask();
        }
        else
        {
            Console.WriteLine("\nThat is not a valid number...");
            Console.WriteLine("Please try again:");
            Console.WriteLine("~enter to continue~");
            Console.ReadLine();
            coinTask();
        }

更改行:

int value;
if (int.TryParse(line, out value))

至:

uint value;
if (uint.TryParse(line, out value))

这样,您只接受 0 和正整数。

您可以在解析后查看该值:

if (int.TryParse(line, out value) && value >= 1)