如果我在嵌套的if语句中添加else,则遇到计数器问题

时间:2017-06-10 16:40:03

标签: vb.net vb.net-2010

如果我在我的计数器不起作用的情况下尝试在退出后放一个别人,我可以找到名字而不是其他名字。如果用户输入了错误的名称,我想让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

结束班

2 个答案:

答案 0 :(得分:1)

在这种情况下,我建议使用 1 1 2 1 2 3 语句,因为您循环遍历需要标识符的集合。因此,不要创建单独的计数器,只需使用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(或对象)。如果您想查找对象而不是仅仅检测名称是否存在。

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

index

答案 1 :(得分:0)

您需要使用th found布尔标志来告诉您是否找到了名称。您在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