2013-02-01 142 views
1

我想在Visual Basic中使用for循環將字符串變量與字符串數組的元素進行比較。我將按照順序將用戶輸入的字符串變量與小寫字母的數組進行比較。我有一些邏輯上的錯誤,因爲我的「count」變量總是出於某種原因,因此它總是會說「Sorry,Try again」,除非用戶輸入Z.請幫忙!比較字符串與數組

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 

回答

1

的問題是,你應該退出循環(與exit for)找到匹配後。否則,任何不匹配的字符都會將txtResults.Text重置爲「對不起,再試一次」。例如,當您輸入「f」時,txtResults.Text設置爲「正確」。但是,當你到達目前,它將txtResults.Text更改爲「對不起,再試一次」,和h,i等。

這是一個很好的編程練習,但有一個快捷方式可以使用:

lower.contains(input.lower) 

信息:

http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx

+0

非常感謝您! – user1959628

1

歡迎來到StackOverflow!

只有當您輸入「z」纔會得到「正確」結果的原因是「z」是數組的最後一項。如果輸入「y」,則結果對於count = 24(lower(24)=「y」)是正確的,但是在下一步它會將「y」與實際爲「z」的較低(25)進行比較。所以txtResult.Text將被「對不起,再試一次」覆蓋。

由於我正確地得到你的任務,你想檢查輸入字符串是否存在於數組中。爲了這個目的,你可以使用Array.Contains方法:

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"} 
Dim input As String = txtInput.Text 
If (lower.Contains(input)) Then 
    txtResult.Text = "Correct" 
Else 
    txtResult.Text = "Sorry, Try again" 
End If