I.Johnson
I.Johnson

Reputation: 21

Why do both of the random numbers I create be the same everytime in visual basic?

Why are RandomInt1 and RandomInt2 always the same number each time I run my code?

    Dim RandomGen1 As New Random
    Dim RandomInt1 As Integer
    RandomInt1 = RandomGen1.Next(2, 7)

    Dim RandomGen2 As New Random
    Dim RandomInt2 As Integer
    RandomInt2 = RandomGen2.Next(2, 7)

Upvotes: 0

Views: 254

Answers (1)

Zabi
Zabi

Reputation: 1369

Mind-blowing fun fact: there is no such thing as a truly random number in computers, the .NET framework's implementation of this concept has a relationship to your problem.

When you start your program using .NET, each random number generator you make (within a given scope) will yield the same sequence of numbers. The sequence of results you will get were already determined, when your program started, by a seed that was somehow selected by the instance. Any randomization that starts with this seed yields the same sequence of numbers. It's fate.

The solution is to use only one "generator" (or "fate processor") and just keep calling the .Next method when you need a new number. Your project sounds cool, but I edited your post to be as clear as possible. Good luck:

    Dim RandomGen1 As New Random
    Dim RandomInt1 As Integer
    RandomInt1 = RandomGen1.Next(2, 7)

    'notice I did not make a RandomGen2, it will just give me the same numbers as RandomGen1
    Dim RandomInt2 As Integer
    RandomInt2 = RandomGen1.Next(2, 7)

Upvotes: 4

Related Questions