有人可以告诉我发生了什么事吗?
当按下Label1
时,我试图在Button1
中显示一个随机问题。我只想让每个问题出现一次。
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 :(得分: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
保持不变。当randomValue.Next(0, Qtn.Length)
降为2或1个元素时,list
很有可能产生越界值。