C#:如何创建仅接受 0 或更大整数值的程序

本文关键字:整数 程序 何创建 创建 | 更新日期: 2023-09-27 18:33:45

对于程序,如果用户输入的数字不是 0 或更高的数字,则程序会说"无效。输入一个 0 或更大的数字。然后程序将继续说"无效。输入一个 0 或更高的数字",直到输入 0 或更高的数字。

问题是,如果我输入一个字母,程序不会响应"无效。输入一个 0 或更大的数字。

到目前为止,我只能这样做:

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

C#:如何创建仅接受 0 或更大整数值的程序

你需要

某种循环。也许是一个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();
}

你的 if 替换为:

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

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

while (Convert.ToInt32(Console.ReadLine()) < 0)
{
    Console.WriteLine("Invalid entry");
}
//Execute code if entry is correct here.

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