2016-07-24 70 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)'来代替。 –

相关问题