使用for循环比较字符串变量和字符串数组

编程入门 行业动态 更新时间:2024-10-20 03:25:00
本文介绍了使用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循环比较字符串变量和字符串数组

本文发布于:2023-11-22 06:22:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616303.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数组   变量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!