开发者

Randomize() in vb.net not randomizing properly

What is wrong with this code? It is called in groups of four, and always seems to wind up with only two combinations:

Public Function GetRand() As String
        Randomize()
        Dim r As Integer = CInt(Rnd() * 3开发者_如何学编程)
        Select Case r
            Case 0
                Return str1
            Case 1
                Return str2
            Case 2
                Return str3
            Case 3
                Return str4
            Case Else
                Return str1
        End Select
    End Function

It is returning random strings, but it seems to be returning them in a non-random order?


Definately chaeck out the Random object that @zawaideh mentions:

    Static R As New Random()  'Static so that it only gets initialized once'
    R.Next(0, 4)              'Returns an integer from zero up to but not including 4, so 0,1,2,3'


The problem probably is the call to Randomize(). Take it out and it should work fine. When calling Randomize(), you are setting the seed the random number generator will use. You should only call it once, otherwise you might be seeding it always with the same value.


If you're using VB.Net you can use the .net random number generator

Dim random_object As New Random()
Console.WriteLine(random_object.Next().ToString())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜