2012-04-29 97 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