2016-07-24 10 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

스택 오버플로에 오신 것을 환영합니다! 나는 당신의 문제를 추측 할 수있는 한 귀하의 질문을 편집했습니다. 그러나 주제에 대한 지식이있는 사람들이 더 많이 볼 수 있도록 코드와 설명을 추가하십시오. 특정 문제를 식별하는 데 필요한 경우 특정 오류 메시지를 편집하십시오. [이 질문에]보십시오 (http://stackoverflow.com/questions/2306742/index-was-out-of-range-must-be-non-negative-and-less-than-the-size-of - 동료)도. 행운을 빕니다! – 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)'를 대신 수행하는 것입니다. –