0

我有以下函数,它接受输入txtbox1并将结果输出到txtbox2. 要点是将每个字母替换为特定的数值,计算每个单词的值,然后显示所有单词的总和。现在,这个函数总是计算到 13。如果我输入aaa bbb cc例如,结果应该是。我该如何修改函数来做到这一点?

aaa = 3
bbb = 15
cc = 14
Total = 32

Private Sub CountLetters(Input As String)

    Dim total As Integer = 0
    Dim dicLetters As New Dictionary(Of Char, Integer)
    dicLetters.Add("a", 1)
    dicLetters.Add("b", 5)
    dicLetters.Add("c", 7)

    For Each word As String In Input.Split

        Dim wordtotal As Integer = 0
        For Each cc As KeyValuePair(Of Char, Integer) In dicLetters

            wordtotal += cc.Value
        Next

        total += wordtotal

        'Display word totals here

        txtBox2.Text += word.PadRight(12) + "=" + _
                        wordtotal.ToString.PadLeft(5) + vbNewLine
    Next

    'Display total here
    txtBox2.Text += "Total".PadRight(12) + "=" + total.ToString.PadLeft(5)
End Sub
4

2 回答 2

4

正如逻辑学家指出的那样,问题在于您遍历字典并总结键的值,而不是单词的值。

如果每个字母都有一个值,那么 Dictionary 是一个不错的方法(如果它只有几个字母,那么 aSelect也可以)。

下面是一些代码,可以得到你正在寻找的结果:

Dim total As Integer = 0
Dim wordTotal AS Integer
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("a", 1)
dicLetters.Add("b", 5)
dicLetters.Add("c", 7)

' charValue will be used to hold the result of the TryGetValue below
Dim charValue As Integer

For Each word As String In Input.Split(New Char() { " " })

    wordTotal = 0

    ' Loop through the word
    For Each character As Char in word

        wordTotal += If(dicLetters.TryGetValue(character, charValue) = _
                     True, dicLetters(character), 0)
    Next

    total += wordTotal

    txtBox2.Text += word.PadRight(12) + " = " + _
                    wordTotal.ToString().PadLeft(5) + vbNewLine
Next

txtBox2.Text += "Total:".PadRight(12) + " = " + _
                total.ToString().PadLeft(5)

外部循环本质上是相同的 - 在“”(空格)上拆分输入字符串。

将 wordTotal 计数器重置为 0,然后循环遍历当前单词(使用 For Each Character 一次遍历一个字符)。

下一行使用TryGetValue字典,如果键有值,则将值添加到 中wordTotal,否则添加 0。

“aaa bbb cc”的输出将是:

aaa = 3
bbb = 15
cc = 14
总计:= 32
于 2013-07-02T03:43:40.693 回答
1

这里有一个提示:你在这个声明中做了什么:

For Each cc As KeyValuePair(Of Char, Integer) In dicLetters
wordtotal += cc.Value
Next

对于字典中的每个键值对,将它们加起来......所以它加起来 1、5 和 7,得到 13。

为什么不使用 SELECT/CASE 语句检查字典中每个字母的值并将其添加到wordtotal

于 2013-07-01T23:23:32.087 回答