Do Until循环检查重复项不会停止循环

时间:2015-03-19 01:51:46

标签: vb.net

我正在尝试执行Do Until循环来检查我的组合框中的重复项。它运行循环,但它永远不会停止循环。

    Dim i As Integer = 0
    Dim flavors As Integer = flavorsComboBox.Items.Count

    Do Until (i < flavors - 1)
        If flavors = flavorsComboBox.Items.Count Then
            MessageBox.Show("Flavor Already Exists!", "Error")
        Else
            flavorsComboBox.Items.Add(flavorsComboBox.Text)
        End If
    Loop

4 个答案:

答案 0 :(得分:1)

循环的条件查看i变量和flavors变量:

Do Until (i < flavors - 1)

但是这些变量在循环体中的任何一点都不会发生变化:

   If flavors = flavorsComboBox.Items.Count Then
        MessageBox.Show("Flavor Already Exists!", "Error")
    Else
        flavorsComboBox.Items.Add(flavorsComboBox.Text)
    End If

您需要添加代码来更改其中一个或两个变量。但这仍然是很难做到的。只需使用Distinct()方法:

Dim items = flavorsComboBox.Items.Distinct().ToArray()
flavorsComboBox.Items.Clear()
flavorsComboBox.Items.AddRange(items)

答案 1 :(得分:0)

这是一个简单的直到循环

Dim i as integer = 0
Dim flavors as Integer = 10

do until (i > flavors -1)
    Console.WriteLine(i.ToString())

    i = i +1
loop

输出

0
1
2
3
4
5
6
7
8
9

在您的代码中:

do until (i < flavors - 1)

如果i = 0并且当0大于count时,flavor为Count -1,则输入循环的条件。

下一个遗漏是你永远不会改变循环的条件变量的值,以准确评估停止循环的条件。

答案 2 :(得分:0)

试试这个:

Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If AddDistinct(flavorsComboBox, "test") Then
            MsgBox("Item did not exist, so it was added.")
        Else
            MsgBox("Item already existed, so it was not added.")
        End If
    End Sub
    Public Function AddDistinct(cboBox As ComboBox, value As Object) As Boolean
        If cboBox.Items.IndexOf(value) = -1 Then cboBox.Items.Add(value) : Return True
        Return False
    End Function
End Class

答案 3 :(得分:-1)

您没有重置flavor的值

试试这个:

Dim i As Integer = 0
Dim flavors As Integer = flavorsComboBox.Items.Count

Do Until (i < flavors - 1)
    If flavors = flavorsComboBox.Items.Count Then
        MessageBox.Show("Flavor Already Exists!", "Error")
    Else
        flavorsComboBox.Items.Add(flavorsComboBox.Text)
        flavors = flavorsComboBox.Items.Count
    End If
Loop