如何将Console.ReadLine循环到无限?

问题描述

您好,我正在尝试创建一个计算器游戏,但是它仅循环2次,(直到为什么)直到用户找到带有输入的结果。稍后,我将介绍如何制作数字的随机生成器,而不是自己在代码中编写数字。请帮忙。

Yassine

using System;

namespace G
{
    class Program
    {
        static void Main(string[] args)
        {

            Calcul(2,2);
        }
        static void Calcul(int nombre1,int nombre2)
        {

            int result = nombre1 + nombre2;
            
            Console.WriteLine("Combien font " + nombre1 + " + " + nombre2);

            int supposed = int.Parse(Console.ReadLine());

            if(result != supposed)
            {
                Console.WriteLine("Try again!");
                supposed = int.Parse(Console.ReadLine());
              
            }
            else 
            {
                Console.Clear();
                Console.WriteLine("Correct!");
            }



        }
    }
}

解决方法

您可以将if语句更改为while循环,其条件是输入与结果不匹配。我们还可以将int.TryParseConsole.ReadLine一起使用,以处理用户未输入有效数字的情况。这可以通过使用out参数来实现,如果成功,该参数将设置为已解析的值,然后返回表示成功的bool。完美的循环条件!

然后,您可以在while循环的主体之后 后面添加“成功”消息(因为退出循环的唯一方法是获得正确的答案)。看起来像这样:

static void Calcul(int nombre1,int nombre2)
{
    int result = nombre1 + nombre2;
    int input;

    Console.Write($"Combien font {nombre1} + {nombre2} = ");

    while (!int.TryParse(Console.ReadLine(),out input) || input != result)
    {
        Console.WriteLine("Incorrect,please try again.");
        Console.Write($"Combien font {nombre1} + {nombre2} = ");
    }

    Console.WriteLine("Correct! Press any key to exit.");
    Console.ReadKey();
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...