Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: VB.NET arrays strings
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-Feb-13 4:43am

1 solution

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

Solution 1

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.
 
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.
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 190
1 Jochen Arndt 155
2 PIEBALDconsult 150
3 Afzaal Ahmad Zeeshan 120
4 DamithSL 115
0 OriginalGriff 5,695
1 DamithSL 4,591
2 Maciej Los 4,012
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,190


Advertise | Privacy | Mobile
Web04 | 2.8.141220.1 | Last Updated 1 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

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