gpt4 book ai didi

C#:如何创建一个只接受 0 或更高整数值的程序?

转载 作者:太空宇宙 更新时间:2023-11-03 20:12:25 27 4
gpt4 key购买 nike

对于该程序,如果用户输入的不是 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();
}
}
}
}

最佳答案

您需要某种循环。可能是一个 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();
}

关于C#:如何创建一个只接受 0 或更高整数值的程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19171219/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com