使用for循环比较字符串变量和字符串数组 [英] Comparing string variable with string array using for loop

查看:95
本文介绍了使用for循环比较字符串变量和字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

您好,



您的问题在于您的IF结构逻辑。

你应该尝试在循环之前将txtResult初始化为最坏的情况,并在l中更改其值只有你有效地找到了价值。

另外,我会在循环外提取inpu。



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



您的问题是因为即使你找到了用户输入的值你也会继续循环,它会在下一个循环中被覆盖,除非输入的值是Z.

input - > A

循环0 - >正确

循环1 - >对不起

循环2 - >对不起...

当输入Z时:

输入 - > Z

loop 0 - >对不起

循环1 - >对不起

....

loop 25 - >正确



当我找到值时,我在循环中添加的退出指令确保你停止循环。



希望这个解释可以帮助你。


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.


这篇关于使用for循环比较字符串变量和字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆