2012-04-29 166 views
0

嗯,我有一些困難,搞清楚我做錯了什麼。 基本上我需要刪除未滿avarage listBox1中的項目,但它給我:Visual basic 2010從列表框中刪除

System.ArgumentOutOfRangeException了未處理 消息= InvalidArgument =的「9」值是無效的「索引」。 參數名稱:index

Private Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.Click 
    Dim Myrand As New Random 
    Dim res As Double 
    Dim i As Integer 
    Dim n As Integer 
    Dim tot As Double 
    Dim avarage As Double 

    ListBox1.Items.Clear() 

    For i = 0 To 14 Step 1 
     res = Math.Round(Myrand.NextDouble, 3) 
     ListBox1.Items.Add(res) 
     tot = tot + res 
    Next 

    avarage = tot/ListBox1.Items.Count 
    MsgBox(avarage) 

    For i = 0 To ListBox1.Items.Count - 1 Step 1 
     If ListBox1.Items(i) < avarage Then 
      ListBox1.Items.RemoveAt(i) 
      n = n + 1 
     End If 
    Next 

    MsgBox("Removed " & n & " items!") 
End Sub 

有什麼建議嗎?

回答

1

它是在對/ Next循環和doesn't reevaluate it開始抓住最大計數。試着從你未去的地方去除你從那裏去掉的方式。

For i = ListBox1.Items.Count - 1 To 0 Step -1 
    If ListBox1.Items(i) < avarage Then 
     ListBox1.Items.RemoveAt(i) 
     n = n + 1 
    End If 
Next 

從以上MSDN鏈接重點礦山:

When a For...Next loop starts, Visual Basic evaluates start, end, and step. This is the only time it evaluates these values. It then assigns start to counter. Before it runs the statement block, it compares counter to end. If counter is already larger than the end value (or smaller if step is negative), the For loop ends and control passes to the statement following the Next statement. Otherwise the statement block runs.

+0

是的,這是趕上...謝謝! – enflam3

+0

@ enflam3很高興爲您提供幫助 –

1

當您刪除一個項目時,它不再位於列表中,因此列表變短,原始計數不再有效。只是遞減i

Private Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.Click 
    Dim Myrand As New Random 
    Dim res As Double 
    Dim i As Integer 
    Dim n As Integer 
    Dim tot As Double 
    Dim avarage As Double 

    ListBox1.Items.Clear() 

    For i = 0 To 14 
     res = Math.Round(Myrand.NextDouble, 3) 
     ListBox1.Items.Add(res) 
     tot += res 
    Next 

    avarage = tot/ListBox1.Items.Count 
    MsgBox(avarage) 

    For i = 0 To ListBox1.Items.Count - 1 
     If ListBox1.Items(i) < avarage Then 
      ListBox1.Items.RemoveAt(i) 
      i -= 1 
      n += 1 
     End If 
    Next 

    MsgBox("Removed " & n & " items!") 
End Sub 
+0

即使通過遞減我我有相同的錯誤信息:System.ArgumentOutOfRangeException了未處理 消息= InvalidArgument =的「7價值'對'索引'無效。 參數名稱:索引 – enflam3

+0

嗯...你不應該這樣。錯誤發生在哪條線上? – Ryan

+0

感謝您幫助和簡化我的代碼!它現在工作,當我改變,對於下一個循環 – enflam3