2014-12-07 81 views
0

有人可以告訴我如何在Visual Basic 2008中創建數字出現次數的應用程序嗎?程序應該提示用戶輸入一個號碼,然後統計用戶號碼中每個號碼(0-9)的出現次數。例如,將打印出122378個數字: 0 = 0,1 = 1,2 = 2,3 = 1,4 = 0,5 = 0,6 = 0,7 = 1,8 = 1,9 = 0, 它說,像字符串一樣對待數字,答案應顯示在列表框中。如何計算出現次數

回答

0

還有其他的方法來做到這一點,但這樣你就明白 - 這樣做:

'prepare placeholder 
dim dict as New Dictionary(of String, Integer) 
dict.Add("0", 0) 
dict.Add("1", 0) 
dict.Add("2", 0) 
dict.Add("3", 0) 
dict.Add("4", 0) 
dict.Add("5", 0) 
dict.Add("6", 0) 
dict.Add("7", 0) 
dict.Add("8", 0) 
dict.Add("9", 0) 

' Assuming you ask user to type into text box txtSubmittedNumber 
' Parse your numbers and collect counts 
For Each c as Char in txtSubmittedNumber.Text.ToCharArray() 

    Dim key as String = c.ToString() 
    dict(key) = dict(key) + 1 

Next 

' Assuming you fill results into listbox lstNumbers, just add your strings to display 
For each kvp as KeyValuePair(of String, Integer) in dict 

    lstNumbers.Items.Add(kvp.Key & "=" & kvp.Value.ToString()) 

Next 

這是初學者的程序。當然有Linq,但它不會清楚發生了什麼,因爲它會替換循環,分組等。