Sérgio Wilker
Sérgio Wilker

Reputation: 157

Random Name Generator

I'm trying to create a random name generator that actually chooses one of the names listed by me and places it in Textbox1, the problem is that it's not randomizing the choices, it's just always following the same order...

First click: Pedro Ribeiro

Second click: Paulo Lins

Third click: Rodrigo Martins

Etc...

Form

enter image description here

Name Code

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...

Last name Code

Dim LastNameKey As Integer
LastNameKey = Int(Rnd() * 10)
Select Case LastNameKey
    Case 0
        TextBox2.Text = "Monteiro"
    Case 1
        TextBox2.Text = "Ferraz"
    Case 2
        TextBox2.Text = "Lins"
Etc...

Upvotes: 0

Views: 2135

Answers (1)

P.Manthe
P.Manthe

Reputation: 960

Here is one of the many ways to achieve what you want. I created a simple structure to properly handles the information.

'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

Upvotes: 2

Related Questions