2016-07-24 116 views
0

有人可以告訴我發生了什麼事嗎?指數超出範圍,必須是非負數,並小於集合的大小

我試圖在Button1被按下時在Label1中出現一個隨機問題。我只想讓每個問題出現一次。

Dim Qtn(4) As String 
Private Sub LoadQs() 
    Qtn(0) = "What is 1 + 10?" 
    Qtn(1) = "What is 1 + 11?" 
    Qtn(2) = "What is 1 + 12?" 
    Qtn(3) = "What is 1 + 13?" 
    Qtn(4) = "What is 1 + 14?" 
End Sub 
Private Sub RndQtn() 
    Dim list As New ArrayList 
    For i As Integer = 0 To 4 
     'Add the numbers to the collection. 
     list.Add(i) 
    Next i 
    Dim randomValue As New Random 
    Dim index As Integer 
    Dim item As Object 
    'Display the items in random order. 
    While list.Count > 0 
     'Choose a random index. 
     index = randomValue.Next(0, Qtn.Length) 
     'Get the item at that index. 
     item = list(index) 
     'Remove the item so that it cannot be chosen again. 
     list.RemoveAt(index) 
     'Display the item. 
     Label1.Text = Qtn(item) 
    End While 
End Sub 
+0

歡迎來到Stack Overflow!我儘可能地猜測你的問題,然後編輯你的問題。但是,添加代碼和說明以便更多知道該主題的人員將看到它。如果需要識別特定問題,請編輯您遇到的特定錯誤消息。看看[這個問題](http://stackoverflow.com/questions/2306742/index-was-out-of-range-must-be-non-negative-and-less-than-the-size-of -the-colle)。祝你好運! – manetsus

回答

2

我不知道VB,但在這個代碼

index = randomValue.Next(0, Qtn.Length) 
    'Get the item at that index. 
    item = list(index) 
    'Remove the item so that it cannot be chosen again. 
    list.RemoveAt(index) 

你的基礎上Qtn長度生成索引,但用它來索引list,這是一個不同的變量。並且因爲你做list.RemoveAt(index)list不斷縮小,但Qtn.Length保持不變。當list下降到2或1個元素時,極有可能randomValue.Next(0, Qtn.Length)會產生越界值。

+0

你是對的。正如你指出的那樣,修正只是簡單地用'randomValue.Next(0,list.Length)'來代替。 –

相關問題