2013-04-25 429 views
-1

我試圖使用此腳本將來自文本框的用戶輸入與22個正確的單詞進行比較。我不是在尋找多個案例,例如VICEADVICE,所以它會是2個值; 我希望它的字符串值只接受相等的值將字符串與數組中的字符串進行比較

目前,它只識別第一個單詞TIED並顯示一個消息框「found」,但它不會識別列表中的任何其他單詞。

我在Visual Basic腳本

Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click 
    Dim StrCorrect() As String = {"TIED", "VICE", "ICED", "DIVE", "DIET", "DATE", "CITE", "CAVE", "AIDE", "ACED", "CITED", "ACTED", "VACATE", "CATTIE", "ADVICE", "AVIATE", "ACTIVE", "VACATED", "DICTATE", "AVIATED", "ACTIVATE", "ACTIVATED"} 
    Dim Find As String = userinput 
    For Each Str As String In StrCorrect 
     If StrComp(Str, userinput, CompareMethod.Text).ToString = 0 Then 
      MsgBox("Found" & userinput) 
      Return 
     Else : MsgBox("incorrect word") 
      Return 
     End If 
    Next 
End Sub 
+1

您可能要更何況你是語言寫這個。'visual-studio'不是一種語言。 – Yakk 2013-04-25 15:29:33

+0

我的VB有點生疏,但是你不想用圓括號代替大括號嗎? – Melanie 2013-04-25 15:38:21

+0

'我希望它的字符串值只接受相等的值.'相等的值並不意味着'VICE' ='Vice' – 2013-04-25 16:05:09

回答

1

的問題是,你的循環被明確地返回,如果第一項不匹配。你只知道你沒有一個匹配,如果你的循環沒有找到一個完成,所以嘗試這樣的事情,而不是:

For Each Str As String In StrCorrect 
    If StrComp(Str, userinput, CompareMethod.Text).ToString = 0 Then 
     MsgBox("Found" & userinput) 
     Return 
    End If 
Next 

MsgBox("incorrect word") 

這將只顯示「不正確的字:」如果項目的所有您的列表第一次測試失敗。

+0

謝謝你,這個答案做到了! – ReCeSSiVE 2013-04-25 15:52:41

0

爲什麼STRCOMP寫?爲什麼不直接比較,如果你想精確匹配?

For Each Str As String In StrCorrect 
     If Str = Find Then 
      MessageBox.Show("Found :" & Str) 
     End If 
    Next 
+0

非常有用,但不能解決問題中提到的問題:「它只是認識到第一個單詞「TIED」,同樣值得注意的是,使用'='省略了可能需要的任何文化和區分大小寫選項 - 對於這些操作使用'string'類的方法通常是更好的做法 – 2013-04-25 15:45:22

+0

它只是應該識別精確匹配而不是'ADVICE'從問題中看到這個'我希望它的字符串值只接受相等的值。' – 2013-04-25 15:45:57

0

我會用一個for循環,像

For i As Integer = 0 To StrCorrect.Length - 1 
     If StrCorrect(i) = Find Then 
      MsgBox("Found" & Find) 
      Return 
     'End if 

     'The else statement simply alerting that it didnt find the right word on this iteration 
     'The else can be removed if you dont want this alert 
     Else 
      MsgBox("incorrect word") 
      'Return 
     End If 
Next 
+0

這根本不會改變問題的結果 – 2013-04-25 15:46:50

+0

它循環遍歷ENTIRE數組,MsgBox表示不正確的單詞只是提醒...一旦它找到合適的單詞就會停止... – tymeJV 2013-04-25 15:47:56

0

嘗試像下面,它會幫助你...

樣品:

Dim result As String() = Array.FindAll(StrCorrect, Function(s) s.Equals(Find)) 
If (result.Length > 0) Then 
    MsgBox("Found : " & userinput) 
Else 
    MsgBox("incorrect word") 
End If 

全碼:

Dim StrCorrect() As String = {"TIED", "VICE", "ICED", "DIVE", "DIET", "DATE", "CITE", "CAVE", "AIDE", "ACED", "CITED", "ACTED", "VACATE", "CATTIE", "ADVICE", "AVIATE", "ACTIVE", "VACATED", "DICTATE", "AVIATED", "ACTIVATE", "ACTIVATED"} 
Dim Find As String = userinput 
Dim result As String() = Array.FindAll(StrCorrect, Function(s) s.Equals(Find)) 
If (result.Length > 0) Then 
    MsgBox("Found : " & userinput) 
Else 
    MsgBox("incorrect word") 
End If 
相關問題