-2

I'm trying to figure out how to generate 3 different random numbers between 50 and 100 using visual basic. My code only prints out the same number three times.

Dim number As Integer
number = rndNumber.Next(50, 100)

lblATime.Text = number.ToString
lblBTime.Text = number.ToString
lblCTime.Text = number.ToString
user692942
  • 16,398
  • 7
  • 76
  • 175
redraider
  • 1
  • 2
  • 1
    Read [the documentation](https://learn.microsoft.com/en-us/dotnet/api/system.random?view=netcore-3.1). "However, on the .NET Framework only, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that **produce identical sequences of random numbers**." – user692942 Sep 13 '20 at 14:27
  • Does this answer your question? [Vb.net Random Number generator generating same number many times](https://stackoverflow.com/q/7456477/692942). – user692942 Sep 13 '20 at 14:33

2 Answers2

4

You are storing a random number in number variable and displaying it three times.

If you want 3 different numbers, call it thrice

lblATime.Text = rndNumber.Next(50, 101).ToString
lblBTime.Text = rndNumber.Next(50, 101).ToString
lblCTime.Text = rndNumber.Next(50, 101).ToString

Also, from the docs,

Next(minValue, maxValue) returns random integers that range from minValue to maxValue - 1. However, if maxValue equals minValue, the method returns minValue.

So, use Next(50, 101) if you want to include both 50 & 100.

AvyChanna
  • 336
  • 5
  • 12
  • 1
    It’s more likely using the same seed -"However, on the .NET Framework only, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce **identical sequences of random numbers**.". – user692942 Sep 13 '20 at 14:31
  • @Lankymart While using the same seed is a common problem, the posted code is doing exactly what this answer says: taking one random number and displaying it three times. – Craig Sep 14 '20 at 13:54
2

The line number = rndNumber.Next(50, 100) does NOT set up a "relation" between number and that expression, meaning it does NOT re-execute that expression every time you access number.

Rather, when the app reaches that line, it executes rndNumber.Next(50, 100) once and assigns the resulting (integer) value to the variable number. Until you assign something else, that number will keep its assigned value. That is why all three Text properties get the same value.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111