我希望程序要求用户一次又一次地输入数字,直到格式异常不存在.

static void Main(string[] args)
{
    int userGuess1 = 0;
    int userGuess2 = 0;

    do
    {
        try
        {
            Console.WriteLine("Welcome to the game. To win User 2 must guess the number User 1 inputs!");
            Console.WriteLine("User 1, Guess a number between 1 and 10 : ");
            userGuess1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("User 2, Guess a number between 1 and 10 : ");
            userGuess2 = Convert.ToInt32(Console.ReadLine());

            if (userGuess2 < userGuess1)
            {
                Console.WriteLine("Your guess is too low.");
            }
            else if (userGuess2 > userGuess1)
            {
                Console.WriteLine("Your guess is too high.");
            }
        }
        catch (FormatException e)
        {
            Console.WriteLine("Please enter numbers between 1 and 10 only.");
            Console.ReadKey();
        }
    }
    while (userGuess1 != userGuess2);

    Console.WriteLine("Congratulations! You won!");
    Console.ReadKey();
}

我无法让程序再次循环.当出现格式异常时,它将退出.我try 移动try和catch语句,但它会产生错误.

推荐答案

最简单的答案是从userGuess1userGuess2的不同值开始.

int userGuess1 = -1;
int userGuess2 = -2;

这是因为当这两个变量相同时,代码退出循环—所以不要在程序开始时将它们设置为相同的.


一个更好的答案是实现这样的方法:

    int ReadInt32()
    {
        int value = 0;
        while (!int.TryParse(Console.ReadLine(), out value) || value < 1 || value > 9)
        {
            Console.WriteLine("Guess a number between 1 and 10 :");
        }
        return value;
    }

这将继续重试一个输入,直到你成功.

现在你的主循环看起来像这样:

    do
    {
        Console.WriteLine("Welcome to the game. To win User 2 must guess the number User 1 inputs!");
        Console.WriteLine("User 1, Guess a number between 1 and 10 : ");
        userGuess1 = ReadInt32();
        Console.WriteLine("User 2, Guess a number between 1 and 10 : ");
        userGuess2 = ReadInt32();

        if (userGuess2 < userGuess1)
        {
            Console.WriteLine("Your guess is too low.");
        }
        else if (userGuess2 > userGuess1)
        {
            Console.WriteLine("Your guess is too high.");
        }
    }
    while (userGuess1 != userGuess2);

请注意,我删除了现在冗余的try/catch.

Csharp相关问答推荐

如何在NServicebus中配置学习传输的文件夹(NService bus 8)

在C#中,DirectoryEntry返回空AuditRules集合,即使审计规则确实存在

在具有主构造函数的类中初始化属性时出现警告

如何在NodaTime中为Instant添加一年?

返回TyedResults.BadRequest<;字符串>;时问题详细信息不起作用

为什么在使用动态obj+类obj时会调用串联?

持有者安全定义未显示在Swagger.NET 8中

为什么无法将对象转换为泛型类型

反序列化私有成员

.NET 8 DI GetServices<;对象&>不工作

Lambda表达式如何与隐式强制转换一起工作?

WPF DataGrid文件名列,允许直接输入文本或通过对话框按键浏览

在C#.NET项目中启动时,如何等待提升的PowerShell进程退出?

.NET 8在appsettings.json中核心使用词典URI、URI&>

如何在Polly重试策略成功之前将HttpClient请求排队?

未显示详细信息的弹出对话框

为什么Swashbakle/Swagger在参数中包含变量名?

Cmd中的&ping.end()";有时会失败,而";ping";总是有效

如何更改Datagridview行标题

如何在.NET8中使用Blazor Web App(WebAssembly)托管服务器端控制器?