首页 > 解决方案 > C#中的连续循环

问题描述

我最近开始学习 C#,并开始根据有关笑话的流程图 ( http://prntscr.com/jo656t ) 制作简单的程序。

然而,当我在“你想听另一个笑话吗?”的流程图中时。我完全不知道如何循环这个。

这是代码。

class Program
{
    static void Main(string[] args)
    { 
        Console.BackgroundColor = ConsoleColor.Black;
        Console.ForegroundColor = ConsoleColor.White;

        string Name;

        Console.WriteLine("What is your name? ");
        Name = Console.ReadLine();
        Console.Write(Name);
        Console.Clear();

        Console.WriteLine("What is your age?");
        int Age = Convert.ToInt16(Console.ReadLine());
        Console.Write(Age);
        Console.Clear();

        string[] jokes = new string[] { "Joke1", "Joke2", "Joke3", "Joke4" };
        int upper = jokes.GetUpperBound(0);
        int lower = jokes.GetLowerBound(0);

        Random rnd = new Random();
        int jk = rnd.Next(lower, upper + 1);     

        if (Age >= 16)
        {
            Console.WriteLine("Do you want to hear a joke?"); 
            string option = Console.ReadLine();

            if (option == "yes")
            {
                Console.WriteLine(jokes[jk]);
                Console.Read();

                Console.WriteLine("Do you want to hear another joke?");
                string option2 = Console.ReadLine();

                int i; 
                if (option2 == "yes")
                {
                    i = 0;
                }
                else
                {
                    i = 1;
                }

                do
                {
                    Console.WriteLine(jokes[jk]);
                    Console.Read();
                } while (i == 0); 
            } 
            else
            {
                Console.WriteLine("Have a nice day, " + Name);
                Console.Read();
            } 
        }
        else
        {
            Console.WriteLine("What a pitty! You're too young to hear this joke!");
            Console.Read();
            Console.WriteLine("Have a nice day, " + Age);
        }
    }

我不知道,因为我完全被困在这一点上,我们将不胜感激。

提前致谢!

标签: c#loops

解决方案


就我个人而言,我会尝试重写代码,使其更具可读性,但这样的事情应该可以工作:

bool keepTellingJokes = true;    

while (keepTellingJokes) 
{
    // your joke code here

    Console.WriteLine("Do you want to hear another joke?");
    string option2 = Console.ReadLine();

    // break out of loop
    if (option2 == "no")
    {
        keepTellingJokes = false;
    } 
}
// code after escaping joke loop

免责声明:我不是每天都写 c#。


推荐阅读