如果我在嵌套的 if 语句中添加 else,计数器会出现问题

Having problems with counter if i add an else in a nested if statement

如果我尝试在退出后添加一个 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

结束Class

您需要使用 found 布尔标志来告诉您名称是否 found.You 在 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 语句,因为您正在遍历需要标识符的集合。因此,与其创建单独的计数器,不如使用 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

举个例子,我删除了 found 布尔值并使用找到的 index(或对象)代替。如果您想查找对象而不是仅仅检测名称是否存在。

另一种方法是使用 Linq(导入 System.Linq):

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