【问题标题】:Arrays don't compare properly数组无法正确比较
【发布时间】:2013-07-05 12:40:51
【问题描述】:

下面的代码没有显示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

【问题讨论】:

  • 请提供'mess'和'win'数组的内容。
  • 您也可以缩短代码 - 默认情况下将标志设置为 true 并仅在不混乱时检查 (i) = win(i)
  • 在 If 上设置断点并单步执行代码。您可能有字符串填充问题,即其中一个字符串有尾随空格。

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


【解决方案1】:

唯一可能的原因是您的数组中的数据未对齐(我无法说出原因,因为您没有提供足够的信息)。如需更简洁的答案,请提供这些数组的内容。

【讨论】:

    【解决方案2】:

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

    如果您编写的代码仅在 mess(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”

    尝试将“for循环”代码修改为以下内容:

    代码 #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
    

    【讨论】:

      猜你喜欢
      • 2012-03-19
      • 1970-01-01
      • 2017-10-19
      • 2019-05-04
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多