2014-09-02 439 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]); 
    } 
} 

這樣,你產生每次運行循環時新的隨機值。