【问题标题】:My code is lying to me我的代码在骗我
【发布时间】:2013-10-26 03:46:48
【问题描述】:

我正在编写一个代码来检查一个单词中是否包含多个相同的字母,因此我将每个字母拆分为一个数组并编写了这段代码。 “correctGuesses”变量应该是重复字母的数量。数组包含字符串 ("H, E, L, L ,O")。

Dim newCharArray() As Char = wordArray(rndNumber).ToCharArray
ReDim Preserve charToString_2(newCharArray.Length - 1)
Dim cBoolean As Boolean = False

For i As Integer = 0 To (newCharArray.Length - 1) Step 1

    charToString_2(i) = newCharArray(i)
    MsgBox(charToString_2(i))

Next



For j As Integer = 0 To (charToString_2.Length - 1) Step 1
    For b As Integer = 0 To (charToString_2.Length - 1) Step 1

        MsgBox("Is " & charToString_2(j) & " = " & charToString_2(b) & "?")

        If j = b Then

            MsgBox(j & " is equal to " & b & ", continuing.")
            Exit For

        End If
        If CStr(charToString_2(b)) = CStr(charToString_2(b)) Then

            MsgBox("Yes, +1")
            correctGuesses += 1
            charToString_2(b) = "Replaced"
            cBoolean = True

        End If

        MsgBox("No, Continuing.")

    Next                    
Next

第一个 if 语句有效,所以只要 j = b,它就会退出并继续。但接下来的循环,它检查“E”是否等于“H”,并返回真!我不知道为什么!

【问题讨论】:

  • 两边都有 b 作为参数。
  • 见鬼,总是那么明显,我很惭愧。
  • @500-InternalServerError 为什么不直接发布答案?

标签: arrays vb.net loops for-loop


【解决方案1】:

你的算法就差不多了。你可以稍微调整一下。

Dim stringtoCheck As String = wordArray(rndNumber)

For j As Integer = 0 To (stringtoCheck.Length - 2)
    For b As Integer = j+1 To (stringtoCheck.Length - 1)

        If stringtoCheck.chars(b) = stringtoCheck.chars(j) Then

            correctGuesses += 1
            cBoolean = True

        End If

    Next                    
Next

【讨论】:

    【解决方案2】:

    这提供了字符串中不同字符的计数。显示外壳。

        Dim wordToCheck As String = "heLlo racecar" 'note L and l
        Dim lettercounts As New Dictionary(Of Char, Integer)
        For Each c As Char In wordToCheck ' .ToUpperInvariant '.ToLowerInvariant
            If Not lettercounts.ContainsKey(c) Then
                Dim ct As Integer = wordToCheck.Count(Function(ch) ch = c)
                lettercounts.Add(c, ct)
            End If
        Next
    
        'show the counts
        For Each ltrct As KeyValuePair(Of Char, Integer) In lettercounts
            Debug.WriteLine(String.Format("{0}  {1}", ltrct.Key, ltrct.Value))
        Next
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 2019-08-02
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      相关资源
      最近更新 更多