Click here to Skip to main content
13,596,891 members
Rate this:
Please Sign up or sign in to vote.
See more:
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"
txtResult.Text = "Sorry, Try again"
End If
Posted 1-Feb-13 3:43am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1


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.

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

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.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web03-2016 | 2.8.180621.3 | Last Updated 1 Feb 2013
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100