数组无法正确比较

时间:2013-07-08 08:41:26

标签: wpf vb.net visual-studio-2012

以下代码未显示You Win!

你能帮我找到问题吗? 两个数组都是字符串。

Sub checkwin()
    Dim flag As Boolean = False
    For i As Integer = 0 To win.Length - 1
        If mess(i) = win(i) Then
            flag = True
        Else
            flag = False
            Exit For
        End If
    Next
    If flag = True Then
        lbl1.Content = "You Win!!"
        Timer.Stop()
        Dim name As String = txtName.Text
        Dim data As String = "insert into puzzleTable([picName], [name], [moves], [time]) values ('mona','" & name & "','" & counter & "','" & x & "')"
        mySql.executeSqlQuery(data)
    End If
End Sub

2 个答案:

答案 0 :(得分:0)

最有可能使用空格填充字符串是你的问题(例如:mess(i)或win(i)填充前导/尾随空格)。请检查数组中的字符串内容,或使用' Trim(mess(i)'

对其进行过滤

如果您正在编写一个代码,只有在混乱(i)中的所有项目与win(i)匹配时才将其定义为win, 请使用以下代码:

代码#1

    Dim flag As Boolean = True    

    'loop will exit and return flag=FASLE if ANY item in mess(i) not match with win(i)
    For i As Integer = 0 To win.Length - 1
        If trim(mess(i)) <> trim(win(i)) Then 'trim added to filter leading/trailing spaces
            flag = False
            Exit For
        End If
    Next

如果您正在尝试编写代码,使用win(i)在mess(i)中找到至少一个匹配项,从而将其定义为“You Win&#39;

尝试修改&#39; for循环&#39;代码如下:

代码#2

    Dim flag As Boolean = False    

    'loop will exit and return flag=TRUE if ANY item in mess(i) matches win(i)
    'else return flag=FALSE if no match was found in all the item in mess(i)
    For i As Integer = 0 To win.Length - 1
        If trim(mess(i)) = trim(win(i)) Then 'trim added to filter leading/trailing spaces
            flag = True
            Exit For
        End If
    Next

答案 1 :(得分:0)

唯一可能的原因是数组中的数据没有对齐(我不能说原因,因为你没有提供足够的信息)。有关更简洁的答案,请提供这些数组的内容。