This question already has an answer here:
Hello all I am trying to figure out why my code below only produces the same random letters/number for all 4/5/8 varibles:
Public Function GenerateRandomString(ByRef iLength As Integer, Optional numberOnly As Boolean = False) As String
If numberOnly Then
Dim RandomClass As New Random()
Dim RememberSet As New HashSet(Of Integer)
Dim RandomNumber As Integer
While RememberSet.Count < 3
RandomNumber = RandomClass.Next(1, 3)
If RememberSet.Add(RandomNumber) Then
Return RandomNumber
End If
End While
Else
Dim rdm As New Random()
Dim sResult As String = ""
Dim allowChrs() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()
For i As Integer = 0 To iLength - 1
sResult += allowChrs(rdm.Next(0, allowChrs.Length))
Next
Return sResult
End If
End Function
And this is the code that I use to test it out:
Private Sub testing()
Dim fourValue1 As String = Nothing
Dim fourValue2 As String = Nothing
Dim fourValue3 As String = Nothing
Dim twelveValue As String = Nothing
Dim eightValue As String = Nothing
fourValue1 = GenerateRandomString(4)
fourValue2 = GenerateRandomString(4)
fourValue3 = GenerateRandomString(4)
twelveValue = GenerateRandomString(12)
eightValue = GenerateRandomString(8)
debug.print(fourValue1)
debug.print(fourValue2)
debug.print(fourValue3)
debug.print(twelveValue)
debug.print(eightValue)
End Sub
And this is what I get for the output for the above code:
Z4Gb
Z4Gb
Z4Gb
Z4Gb5Sq28VOr
Z4Gb5Sq2
So are you see Z4Gb is in each of the random generated variables and then Z4Gb5Sq2 is within the 8 and 12 variables.
So what am I doing incorrect?
Aucun commentaire:
Enregistrer un commentaire