短语生成器不断重复相同的短语

时间:2014-09-02 01:19:27

标签: c#

我对C#很陌生,我认为这将是一个有趣的小挑战。经过大量搜索我遇到同样问题的其他帖子后,没有人能够帮助我。每次我调试它时,短语都不同,但是在调试时,它会重复相同的短语,而不是每次都不同。

using System;

public class Program
{

    static String[] nouns = new String[3] { "He", "She", "It" };
    static String[] adjectives = new String[5] { "loudly", "quickly", "poorly", "greatly", "wisely" };
    static String[] verbs = new String[5] { "climbed", "danced", "cried", "flew", "died" };
    static Random rnd = new Random();
    static int noun = rnd.Next(0, nouns.Length);
    static int adjective = rnd.Next(0, adjectives.Length);
    static int verb = rnd.Next(0, verbs.Length);

    static void Main()
    {
        for (int rep = 0; rep < 5; rep++ )
        {
            Console.WriteLine("{0} {1} {2}", nouns[noun], adjectives[adjective], verbs[verb]);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

静态变量仅在程序首次加载时初始化一次。

每次打印新短语时都需要生成nounadjectiveverb - 因此您应该将它们移动到循环中,如下所示:< / p>

static void Main()
{
    for (int rep = 0; rep < 5; rep++ )
    {
        int noun = rnd.Next(0, nouns.Length);
        int adjective = rnd.Next(0, adjectives.Length);
        int verb = rnd.Next(0, verbs.Length);
        Console.WriteLine("{0} {1} {2}", nouns[noun], adjectives[adjective], verbs[verb]);
    }
}

这样,每次循环运行时都会生成新的随机值。