Reputation: 23
I am trying to compare a string variable to an element of a string array using a for loop in visual basic. I am comparing a user-entered string variable to an array with the lowercase alphabet, in order. I have some logical mistake because my "count" variable is always on 25 for some reason, and therefore it always says "Sorry, Try again" unless the user types a Z. Please help!
Dim lower() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
For count As Integer = 0 To 25
input = txtInput.Text
input = input.ToLower
If input.Equals(lower(count)) Then
txtResult.Text = "Correct"
Else
txtResult.Text = "Sorry, Try again"
End If
Next
Upvotes: 2
Views: 3239
Reputation: 15813
The problem is that you should exit the loop (with exit for
) after you find a match. Otherwise, any mismatched characters will reset txtResults.Text to "Sorry, Try again." For example, when you enter "f", txtResults.Text is set to "Correct". But when you get to g, currently, it changes txtResults.Text to "Sorry, Try again.", and h, i, etc.
This is a good exercise in programming, but there is a shortcut you can use:
lower.contains(input.lower)
Info:
http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx
Upvotes: 1
Reputation: 32459
Welcome to StackOverflow!
The reason you get "Correct" result only if you type "z" is that "z" is the last item of the array. If you type "y", the result will be correct for count = 24 (lower(24) = "y"), but at the next step it compares "y" with lower(25), which is actually "z". So txtResult.Text
will be overwritten by "Sorry, Try again".
As I get your task correctly, you want to check if the input string is exists in the array. For that purpose you may use Array.Contains
method:
Dim lower() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
Dim input As String = txtInput.Text
If (lower.Contains(input)) Then
txtResult.Text = "Correct"
Else
txtResult.Text = "Sorry, Try again"
End If
Upvotes: 1