Vb.net 如果在嵌套的if语句中添加else,则计数器出现问题

Vb.net 如果在嵌套的if语句中添加else,则计数器出现问题,vb.net,vb.net-2010,Vb.net,Vb.net 2010,如果我在计数器不工作的情况下尝试在退出后放置一个else,我可以找到名字,但不能找到其余的名字。如果用户输入了错误的名称,我想用else显示一个消息框。我试过放其他东西,但如果我搜索例如姓氏,它不会工作,因为计数器不会递增。请你能在不改变循环的情况下帮我写代码吗 Dim name(5) As String Dim found As Boolean Dim search As String name(0) = "John" name(1) = "Ken"

如果我在计数器不工作的情况下尝试在退出后放置一个else,我可以找到名字,但不能找到其余的名字。如果用户输入了错误的名称,我想用else显示一个消息框。我试过放其他东西,但如果我搜索例如姓氏,它不会工作,因为计数器不会递增。请你能在不改变循环的情况下帮我写代码吗

    Dim name(5) As String
    Dim found As Boolean
    Dim search As String

    name(0) = "John"
    name(1) = "Ken"
    name(2) = "Jen"
    name(3) = "Fam"
    name(4) = "Denny"

    search = InputBox("search name")
    found = False
    Dim counter As Integer = -1
    While found = False
        counter = counter + 1
        If search = name(counter) Then
            MsgBox("hello")
            Exit While
        End If
    End While
End Sub
End Class

您需要使用找到的布尔标志来告诉您是否找到了名称。您可以在if语句中将其设置为true,然后在循环结束后检查其值。在计数器到达列表中的最后一个元素后,还需要退出while循环

Dim name(5) As String
Dim found As Boolean
Dim search As String

name(0) = "John"
name(1) = "Ken"
name(2) = "Jen"
name(3) = "Fam"
name(4) = "Denny"

search = InputBox("search name")
found = False
Dim counter As Integer = -1
While found = False
    counter = counter + 1
    If search = name(counter) Then
        MsgBox("hello")
        found = True
        Exit While
    End If
    If Counter = name.Length - 1
        Exit While
    End If
End While

If found = True Then
    MsgBox("Name was found")
Else
    MsgBox("Name was not found")
End If

在本例中,我建议使用For-Each语句,因为您在需要标识符的集合中循环。因此,不要创建单独的计数器,只需为每个标识符使用

Dim name(4) As String

name(0) = "John"
name(1) = "Ken"
name(2) = "Jen"
name(3) = "Fam"
name(4) = "Denny"

Dim search = InputBox("search name")
Dim index As Integer = -1

For i = 0 To name.Length - 1
    If name(i) = search Then
        index  = i
        Exit For
    End If
Next

If index > -1 Then
    MsgBox("Name '" + name(index) + "' was found.")
Else
    MsgBox("Name '" + search + "' was not found.")
End If
举个例子,我删除了查找到的布尔值,并使用了查找到的索引或对象。如果您想查找对象,而不是仅仅检测名称是否存在

另一种方法是使用Linq导入系统。Linq:

Dim found = name.Any(Function(n) n.Equals(search, StringComparison.InvariantCultureIgnoreCase))

没有其他语句可以帮助您。请阅读并使用VB.NET的,它应该是Dim name4作为字符串。是的,在这种情况下,退出While是多余的。但是我们确实需要找到的变量来知道它是否是离开循环后找到的搜索,对吗?我删除了我的原始注释,因为它不正确。你需要暂时离开,但不是像这样。如果名称不存在,循环将停止,并出现异常:“System.IndexOutOfRangeException”。您需要测试计数器,并在测试数组中的最后一项后退出循环,