我有以下函数从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
答案 0 :(得分:4)
正如逻辑学家指出的那样,问题是你在字典中循环并总结了键的值,而不是单词的值。
如果你有一个每个字母的值,一个字典是一个很好的方法(如果只有几个字母而不是Select
也可以。)
以下是一些可以获得您正在寻找的结果的代码:
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 Total: = 32
答案 1 :(得分:1)
这是一个提示:你在这个陈述中做了什么:
For Each cc As KeyValuePair(Of Char, Integer) In dicLetters
wordtotal += cc.Value
Next
对于字典中的每个键值对,将它们加起来...所以它加起来1,5和7给你13。
为什么不把SELECT / CASE语句检查字母的每个字母的值并将其添加到wordtotal