2015-04-05 46 views
0

所以,我正在編寫一個函數,它會詢問字典中的一個隨機問題,直到提出所有問題並遇到問題。當隨機生成的數字列表中已經包含新生成的數字時,程序將調用Ask函數,因爲它應該如此。但是,當它到達最後的返回行時,它會再次調用函數Ask,而不是返回數字列表。C#return不會退出函數

 static List<int> Ask(Dictionary<string,string> Questions, List<int> random, int count) 
    { 
     bool contains = false; 
     var rando = new Random(); 
     int num = Convert.ToInt32(rando.Next(0, count)); 

     if (random.Count >= count) 
     { 
      Console.WriteLine("No more questions! Quitting"); 
      System.Environment.Exit(1); 
     } 

     foreach (int number in random) 
     { 
      if (number == num) 
      { 
       contains = true; 
      } 
     } 

     if (contains == true) 
     { 
      Ask(Questions, random, count); 
     } 

     random.Add(num); 
     var randomEntry = Questions.ElementAt(num); 
     String randomKey = randomEntry.Key; 
     String randomValue = randomEntry.Value; 
     Console.WriteLine(randomKey); 

     if (Console.ReadLine() == randomValue) 
     { 
      Console.WriteLine("Correct!"); 
     } 

     else 
     { 
      Console.WriteLine("Wrong!"); 
     } 
     return random; 
    } 
+1

你做了哪些調試來確認這一點?你描述的行爲假設你的邏輯必須是正確的,.NET運行時本身必須從根本上打破。這通常是一個無效的假設。實際上,return語句確實會退出一個方法。如果沒有,*所有*會被打破。 – David 2015-04-05 21:43:34

+0

只是在VS 2013簡單的調試。很抱歉,如果這不能回答你的問題,我還在學習。它從if(contains == true)語句中調用Ask函數,如果有幫助的話。 – 2015-04-05 21:48:14

+0

逐步執行調試器中的執行代碼。如果'contains'是'true',那麼根據你的代碼,它應該遞歸調用'Ask()'函數。那麼,爲什麼你會驚訝它正在做這件事?另外,爲什麼你不用*結果*來調用該函數? – David 2015-04-05 21:49:38

回答

1

我認爲問題出在你的函數Ask的遞歸調用中。當您從遞歸調用中退出時,您之前的調用仍在Ask方法中,並且無法避免Ask調用後面的其餘代碼。
我不認爲你真的需要一個遞歸方法。只是檢查,如果產生的隨機數已經在您的常見問題列表和重複隨機生成,直到找到一個問題之前,不問....

這裏的重構的代碼與變量名容易混淆

List<int> Ask(Dictionary<string,string> Questions, int count) 
{ 
    List<int> askedList = new List<int>(); 
    var rnd = new Random(); 
    int questionIndex = rnd.Next(0, count); 

    while(askedList.Count < count) 
    { 
     if(!askedList.Any(number => number == questionIndex)) 
     { 
      askedList.Add(questionIndex); 
      var questionEntry = Questions.ElementAt(questionIndex); 
      string questionText = questionEntry.Key; 
      string questionAnswer = questionEntry.Value; 
      Console.WriteLine(questionText); 

      if (Console.ReadLine() == questionAnswer) 
      { 
       Console.WriteLine("Correct!"); 
      } 
      else 
      { 
       Console.WriteLine("Wrong!"); 
      } 
     } 
     questionIndex = rnd.Next(0, count); 
    } 
    return askedList; 
} 
+0

謝謝!奇蹟般有效。只有在問完問題後我才需要退出該功能,但這不是一個難以解決的問題。 – 2015-04-05 22:03:36

1

你的代碼有點雜亂。但random var在遞歸調用函數後未更新。試試這個:

random = Ask(Questions, random, count); 
+0

沒有工作,但謝謝。 – 2015-04-05 21:55:51