首页 > 解决方案 > 如何在 C# Coding (Visual Studio) 中添加退出或重试

问题描述

我目前是一名学生,刚刚学习C#。我正在尝试实现一个代码,以便您可以随时键入 exit 或 restart 。我可以弄清楚如何去做或如何接近它。再次,我对编码是全新的,并且在任何帮助之前没有任何背景。谢谢你。我已经发布了一张关于我所拥有的图片。

在此处输入图像描述

标签: c#visual-studiovisual-studio-codevisual-studio-2019

解决方案


根据您的描述,我为猜数字游戏制作了一个代码示例。

我用return退出游戏,用break重试游戏。

代码:

  static void Main(string[] args)
            {
                int attempts = 0;
                int answer = 45;
                int guess = 12;
                bool t = false;
                while(attempts<5)
                {
                    while (true)
                    {
                        Console.WriteLine("Guess a number between 0~100");
                        t = int.TryParse(Console.ReadLine(), out guess);
                        if (t == false)
                        {
                            Console.WriteLine("Your input is not a number, please input again, you have {0} changes",4-attempts);
                            break;
                        }
                        else
                        {
                            if(guess>100||guess<0)
                            {
                                Console.WriteLine("Your input number is not in the range, please input again, you have {0} changes", 4 - attempts);
                                break;
                            }
                            else
                            {
                                if(answer==guess)
                                {
                                    Console.WriteLine("You guessed right");
                                    Console.WriteLine("Game over");
                                    Console.ReadLine();
                                    return;
                                }
                                else
                                {
                                    Console.WriteLine("You gueesed wrong, please input again, you have {0} changes", 4 - attempts);
                                    break;
                                }
                            }
                        }
                    }
                    if (attempts == 4)
                    {
                        Console.WriteLine("You have no chances");
                        Console.WriteLine("Game over");
                        Console.ReadLine();
                        return;
                    }
                        attempts = attempts + 1;
              
                   
                }
    
}

测试结果:

在此处输入图像描述


推荐阅读