如何计算出现次数

时间:2014-12-07 16:51:25

标签: visual-studio

有人可以告诉我如何在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, 它表示将数字视为字符串,答案应显示在列表框中。

1 个答案:

答案 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但是它不会那么清楚,因为它取代了循环,分组等等。