2014-09-02 437 views
0

我对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]); 
     } 
    } 
} 

回答

2

静态变量只会在程序第一次加载时初始化一次。

你需要nounadjective,并verb(重新)每次打印了一个新词时产生的 - 所以你应该将它们移到你的循环里面,像这样:

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]); 
    } 
} 

这样,你产生每次运行循环时新的随机值。