Click here to Skip to main content
15,905,682 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
SQL
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. Can anyone tell me why this is happening or know a more efficient way to do this? Thank you.

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
Posted

1 solution

Hello,

Your problem resides in the logic of your IF construction.
You should try to initialize the "txtResult" to the worst case scenario before the loop and change its value inside the loop only if you effectively find the value.
Also, I would take the extraction of the inpu outside of the loop.

VB
txtResult.Text = "Sorry, Try again"
input = txtInput.Text.ToLower
For count As Integer = 0 to 25
    If input.Equals(lower(count)) Then
        txtResult.Text = "Correct"
        Exit For
    End If
Next

Your problem is that since you keep looping even when you have found the value entered by the user it is overriden in the next loops unless the value entered is Z.
input -> A
loop 0 -> Correct
loop 1 -> Sorry
loop 2 -> Sorry ...
Whereas when Z is entered:
input -> Z
loop 0 -> Sorry
loop 1 -> Sorry
....
loop 25 -> Correct

The "Exit For" instruction I have added in the loop when the value is found makes sure you stop looping.

Hope this explanation helps you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900