Reputation: 3
if I try to put an else after exit while my counter doesn't work, I can find the first name but not the rest. I want to put the else to show a message box if the user has inputted a wrong name. i have tried putting else but if i search for eg the last name it doesn't work because the counter doesn't increments. please can you'll help me with the code without changing the loops.
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
Upvotes: 0
Views: 109
Reputation: 926
You need to use th found
boolean flag to tell you whether or not the name was found.You set it to true within the if statement and then check for its value after the loop ends. You also would need to exit the while loop after the counter reaches the last element in the list.
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
Upvotes: 0
Reputation:
In this case I would recommend to use the For Each
statement, since you are looping through a collection where you need the identifier. So instead of creating a seperate counter, just use the For Each
identifier.
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
Just to give you an example I've removed the found
boolean and used the found index
(or object) instead. In case you want to lookup the object instead of just detecting if the name exists.
An alternative would be to use Linq (Imports System.Linq):
Dim found = name.Any(Function(n) n.Equals(search, StringComparison.InvariantCultureIgnoreCase))
Upvotes: 1