检查输入是否为负整数错误

时间:2015-10-13 07:57:42

标签: c# console-application

我试图制作一个程序,它会从用户那里取一个整数并多次翻转硬币。但是,当用户输入负整数时,程序会遇到溢出异常。'我怎样才能使用户只能输入正整数?

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();
        }

2 个答案:

答案 0 :(得分:4)

更改行:

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

为:

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

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

答案 1 :(得分:0)

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

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