随机名称生成器

时间:2017-11-22 20:21:15

标签: vb.net random

我正在尝试创建一个随机名称生成器,它实际上选择了我列出的名称之一并将其放在Textbox1中,问题是它不是随机选择的,它只是始终遵循相同的顺序... < / p>

首先点击:Pedro Ribeiro

第二次点击:Paulo Lins

第三次点击:罗德里戈·马丁斯

等等...

表格

enter image description here

名称代码

connect

姓氏代码

Dim NameKey As Integer
NameKey = Int(Rnd() * 10)
Select Case NameKey
    Case 0
        TextBox1.Text = "Will"
    Case 1
        TextBox1.Text = "Bernardo"
    Case 2
        TextBox1.Text = "Manoel"
Etc...

1 个答案:

答案 0 :(得分:2)

这是实现目标的众多方法之一。 我创建了一个简单的结构来正确处理信息。

'The structure will ensure coherent data
Public Structure Person
    Public firstName As String
    Public lastName As String
    Public Sub New(fName As String, lName As String)
        firstName = fName
        lastName = lName
    End Sub
End Structure

Public Sub AnySub()

    'You should use lists or dictionaries when you manipulate collections
    Dim ListNames As New List(Of Person)
    ListNames.Add(New Person("Shin", "Juku"))
    ListNames.Add(New Person("Yaki", "Tori"))
    ListNames.Add(New Person("Fuji", "San"))

    'This will initialize and randomize the counter
    'Since the seed is time dependent, the result will be (almost) different each time you call it
    Dim rnd As New Random(Now.Millisecond)

    For i As Integer = 0 To 5
        'index will change at each iteration
        'I specify ListNames.Count as a maximum so I can use it as a counter of ListNames
        Dim index As Integer = rnd.Next(ListNames.Count)

        'retrieve a random person in the list and displaying its information
        Dim current As Person = ListNames(index)
        MsgBox(current.firstName & " " & current.lastName)
    Next

End Sub