2014-10-26 27 views
1

即時嘗試使用隨機數來從30個字符串中取出58個字符串的數組,並且使用布爾數組來檢查並確保相同的數字不會被調用兩次。該方法和程序總是崩潰,索引超出範圍錯誤。這裏是方法。在布爾數組(c#)中超出範圍異常

 static string[] newlist(string[] s) 
     { 
      string[] newlist = {}; 
      bool[] issearched = new bool[s.Length]; 
      Random callorder = new Random(); 
      for (int i = 0; i < 31; i++) 
      { 
       int number = callorder.Next(0, s.Length); 
       if (issearched[number] == false) 
       { 
        newlist[number] = s[number]; 
        issearched[number] = true;//this is where it always crashes even though the ide says issearced has 58 elements and the random number is always smaller than that. 
       } 
       else 
        i--; 
      } 
      return newlist;    
     } 

我確定它的簡單,但我想不出爲什麼8指數是58

+0

的值沒有你的陣列newlist不是58元件長度。 – Steve 2014-10-26 23:57:30

+0

它的[s.length]的長度是58.視覺工作室說58當我在折點處滾動它時。 – vexedpython 2014-10-27 00:01:48

+0

再次檢查issearched的長度不是新列表的長度,您正在分配給newlist而不是issearched,例外情況是在newlist assignement分配 – Steve 2014-10-27 00:09:40

回答

2

你的數組newlist(多麼混亂的名字)沒有空間來存儲任何東西。
此行

string[] newlist = {}; 

聲明數組,但沒有設置空間來存儲任何元素,所以當您嘗試使用索引就可以了你的例外。

我建議使用不同的方法從傳遞的數組中找到30個字符串。
使用List<string>和繼續下去,直到在列表

static string[] newlist(string[] s) 
    { 
     List<string> selectedElements = new List<string>(); 
     bool[] issearched = new bool[s.Length]; 
     Random callorder = new Random(); 
     while(selectedElements.Count < 30)) 
     { 
      int number = callorder.Next(0, s.Length); 
      if (!issearched[number]) 
      { 
       selectedElements.Add(s[number]); 
       issearched[number] = true; 
      } 
     } 
     return selectedElements.ToArray(); 
    } 

30元。如果你喜歡使用陣列添加到這個列表,從你的方法,然後幾個固定的,需要你的代碼

static string[] newlist(string[] s) 
{ 
    string[] newlist = new string[30]; 
    bool[] issearched = new bool[s.Length]; 
    Random callorder = new Random(); 
    for (int i = 0; i < 30; i++) 
    { 
     int number = callorder.Next(0, s.Length); 
     if (issearched[number] == false) 
     { 
      newlist[i] = s[number]; 
      issearched[number] = true; 
     } 
     else 
      i--; 
    } 
    return newlist; 
} 
  • 的newlist陣列被聲明爲有空間來存儲30個元素
  • 的爲30倍(未31從當前代碼)
  • 01環
  • 的newlist應索引使用變量i
+0

謝謝你解決了這個問題。我想我住院的時候讀了什麼IDE說這個問題是正確的,但現在運行。我敢打賭,我看起來愚蠢的大聲笑 - - ^; – vexedpython 2014-10-27 00:15:00

1

數組我相信你的範圍之外,實際上是在崩潰的位置:

newlist[number] = s[number]; 

更換

string[] newlist = {}; 

隨着

string[] newlist = new string[s.Length]; 

您的新建列表大小爲0個元素,無處爲您分配足夠的空間。

如果輸入大小小於31個元素,您的程序也會進入無限循環。

+0

謝謝你做到了。即時通訊仍然是新的編程,並沒有變得太善於調試,所以我一定很想知道ide是在說什麼問題。 – vexedpython 2014-10-27 00:13:21