是什么导致我的main方法无限运行,而我却希望它根据用户的响应递增地运行我的方法?

问题描述 投票:-3回答:2

[我正在尝试编写一个初学者程序,在其中我掷2个骰子,并测试骰子,如果有偶数,它将说“偶数比偶数好”,并且在某些情况下,只有偶数会说,“赔率仍然很酷”,每次掷骰后,它都会询问用户是否要再次玩,否则,它将告诉用户他们掷骰子了多少次。当我运行该程序时,它将运行,并询问用户是否要再次滚动,当我键入“是”时,它将无限运行。我不知道问题是否与主要方法的编写方式有关,或者与TinasDice方法有关。

我已经尝试在测试用户输入的main方法中仅使用if / else语句,但是该语句立即退出程序。

            TinasDice();

            Console.WriteLine("Do you want to play again?");
            string answer;
            int counter = 0;
            answer = Console.ReadLine();

            while (answer == "YES")
            {

                if (answer == "YES")
                {
                    TinasDice();
                }
                else
                {
                    Console.WriteLine("The number of times the dice was die was thrown is: " + counter);
                    Console.WriteLine("Nice game!");
                    Console.WriteLine("Thanks for playing. Come play again soon!");
                }

            }
        }
                public static void TinasDice()
                {
                Random random = new Random();

                int dice1 = new int();
                int dice2 = new int();

                dice1 = random.Next(1, 6);
                dice2 = random.Next(1, 6);

                Console.WriteLine("Hey Welcome to Tina's Dice Game.");
                Console.WriteLine("Let's start!");

                if (dice1 % 2 == 0 || dice2 % 2 == 0)
                {
                    Console.WriteLine("I got  " + dice1 + " and " + dice2);
                    Console.WriteLine("Evens are better then odds!");

                }
                else   
                {
                    Console.WriteLine("I got a " + dice1 + " and " + dice2);
                    Console.WriteLine("Odds ares still cool!");                      
                }      

我只是想让程序在首次运行TinasDice之后逐步运行,所以当用户键入“ YES”时,它将运行一次TinasDice,然后再次提示用户,直到用户键入其他内容为止然后是“是”。

c# loops infinite dice
2个回答
0
投票

从上面举个例子。

   TinasDice();

        Console.WriteLine("Do you want to play again?");
        string answer = "YES";
        int counter = 0;


        while (answer == "YES")
        {
            answer = Console.ReadLine();
            counter++;
            if (answer == "YES")
            {
                TinasDice();
            }
            else
            {
                Console.WriteLine("The number of times the dice was die was thrown is: " + counter);
                Console.WriteLine("Nice game!");
                Console.WriteLine("Thanks for playing. Come play again soon!");
                break;
            }

        }
    }

注意“ YES”和break的默认设置>


-1
投票

您可以尝试以下方法:

© www.soinside.com 2019 - 2024. All rights reserved.