【问题标题】:Index was out of range, must be non-negative and less than the size of the collection索引超出范围,必须为非负数且小于集合的大小
【发布时间】:2016-07-24 19:00:01
【问题描述】:

谁能告诉我这是怎么回事?

当按下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

【问题讨论】:

  • 欢迎来到 Stack Overflow!我尽可能地编辑了你的问题。但是,添加代码和描述,以便更多具有该主题知识的人看到它。请在您遇到的特定错误消息中进行编辑,以防有必要识别特定问题。也看看this question。祝你好运!

标签: vb.net vb.net-2010


【解决方案1】:

我不懂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) 很有可能会产生越界值。

【讨论】:

  • 你是对的。正如您所指出的,修复只是简单地执行randomValue.Next(0, list.Length)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-05
  • 2019-08-28
  • 1970-01-01
相关资源
最近更新 更多