2013-07-01 87 views
0

我有以下函數,其輸入來自txtbox1的輸入並輸出結果txtbox2。要點是用一個特定的數值代替每個字母,計算每個字的值,然後顯示所有字的總數。現在,這個函數總是計算到13.如果我輸入aaa bbb cc例如,結果應該是。我如何修改函數來做到這一點?計算每個字母和總數vb.net

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

由於logixologist指出,這個問題爲y我們遍歷字典並總結鍵的值,而不是單詞的值。

如果你有每個字母的值,一個字典是一個好方法(如果只有幾個字母,那麼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 
+0

謝謝@tim! – logixologist

+0

@logixologist - 不客氣。我希望我沒有偷你的雷霆...... – Tim

+0

我更喜歡你的解決方案:)。 – logixologist

1

這裏有一個提示:你正在做的這個聲明是什麼:

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

對於字典中的每一個鍵值對它們加起來......所以它加起來1,5和7給你13

爲什麼不把一個SELECT/CASE語句檢查對字典中的每個字母的價值,並補充說,到wordtotal

+0

感謝您的提示,但我仍然無法獲得理想的結果。 – user2536008

+0

如何實現select/case語句? – user2536008

+0

執行此操作的更簡單的方法是不使用具有鍵值對的字典,除非您有很多鍵/值對。我現在沒有打開vb.net,但我會盡可能地查看。 – logixologist