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

本文关键字:整数 错误 输入 是否 检查 | 更新日期: 2023-09-27 18:17:19

我正在尝试制作一个程序,该程序将从用户处获取一个整数并投掷硬币多次。但是,当用户输入负整数时,程序会遇到"溢出异常"。我怎样才能让用户只能输入一个正整数?

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)