I created a small vb.net console app in visual studio 2008 trying to learn .net but my results show differently when I break in the code and press F11 to step through. If I do it this way, the results I expect to get show but if I don’t break into the code the results aren’t what I’m expecting.
Basically everytime I click a button i want to write four numbers that are random. If I break into the code, these show random numbers i.e. 1 3 4 3 but if i don’t break into the code. my numbers are all the same i.e. 1 1 1 1.
Here is my code, like I said I’m still learning so the logic is probably not correct.
Module Module1
Dim number1 As Integer = 0
Dim _DiceRolled As Boolean = False
Dim number2 As Integer = 0
Dim number3 As Integer = 0
Dim number4 As Integer = 0
Dim numberArray() As Integer = {number1, number2, number3, number4}
Sub Main()
Dim quit As Boolean = False
Dim cki As ConsoleKeyInfo
Do While quit = False
If diceRolled = False Then
Console.WriteLine("Press any key to roll the dice...")
cki = Console.ReadKey
If cki.KeyChar <> "q" Then
quit = False
Else
quit = True
Exit Do
End If
roll()
diceRolled = True
Else
Console.WriteLine("Press any key to roll the dice again...")
cki = Console.ReadKey
If cki.KeyChar <> "q" Then
quit = False
Else
quit = True
Exit Do
End If
roll()
End If
Loop
Console.WriteLine(" Game is over!")
Console.ReadKey()
End Sub
Private Sub roll()
Dim newNumbers(4) As Integer
Dim stringbuilder As String = ""
Console.Write(" New numbers : ")
Dim count As Integer = 0
stringbuilder = ""
For Each number As Integer In numberArray
newNumbers(count) = (generateRandomNumber(number))
stringbuilder += (newNumbers(count).ToString() + " ")
count += 1
Next
Console.Write(stringbuilder)
End Sub
Private Function generateRandomNumber(ByVal number As Integer)
Dim rand As New Random
number = rand.Next(1, 5)
Return number
End Function
Private Property diceRolled()
Get
Return _DiceRolled
End Get
Set(ByVal value)
_DiceRolled = value
End Set
End Property
End Module
Any ideas? Thanks
You’re making a new
Randominstance for each random number.By default,
Randomcreates a seed from the current time.Your code runs fast enough that all of the
Randoms get the same seed.When you step through it, the steps add pauses between the
Randoms, so they get different seeds.You should reuse the same
Randominstance in aSharedfield.