Angka Acak di VB.NET

Random class udah ada di  .NET Framework class library
di constructornya, ada dua override method. ada yang minta input ada yang gak..

Random class punya tiga public method yaitu : Next, NextBytes, and NextDouble.

Next method mengembalikan angka acak biasa ,
NextBytes mengembalikan array yang berisi angka acak,
NextDouble mengembalikan angka acak untuk nilai desimal

contoh mengembalikan angka acak biasa:

Dim num As Integer = random.Next()

contoh mengembalikan angka acak < 1000.

Dim num As Integer = random.Next(1000)

angka acak diantara:

Private Function RandomNumber(min As Integer, max As Integer) As Integer
   Dim random As New Random()
   Return random.Next(min, max)
End Function 

buat string acak :

Private Function RandomString(size As Integer, lowerCase As Boolean) As String
   Dim builder As New StringBuilder()
   Dim random As New Random()
   Dim ch As Char
   Dim i As Integer
   For i = 0 To size - 1
      ch = Convert.ToChar(Convert.ToInt32((26 * random.NextDouble() + 65)))
      builder.Append(ch)
   Next
   i If lowerCase Then
      Return builder.ToString().ToLower()
   End If
   Return builder.ToString()
End Function 

kombinasi fungsi angka dan string acak diatas (example:password generator)

Public Function GetPassword() As String
   Dim builder As New StringBuilder()
   builder.Append(RandomString(4, True))
   builder.Append(RandomInt(1000, 9999))
   builder.Append(RandomString(2, False))
   Return builder.ToString()
End Function 'GetPassword 
>

1 comments:

Ageng Dwi Prastyawan mengatakan...

Makasih gan, ini yang ane cari cari.

http://rexcarnation.blogspot.com

Poskan Komentar