At times you may need to generate random numbers to fill an array in your Visual Basic applications for testing purposes. Use the "Random" class to generate numbers that meet certain statistical requirements for randomness. The "Random.NextBytes" method fills the elements of a specified array of bytes with random numbers. You can use random numbers to test saving binary data to a file or to a database table without having to read a real file.
- Skill level:
- Moderately Easy
Other People Are Reading
Launch Microsoft Visual Basic Express, click "New Project..." on the left pane of your screen then select "Console Application." Click "OK" to create a new console project.
Create the "Byte" data type array to fill with random numbers by typing the following line of code (capitalisation matters):
Dim my Bytes(150) As Byte
Create the "Random" data type variable to fill the array with random byte values by adding the following line of code:
Dim randomNums As New Random()
Fill the byte array with random numbers by adding the following line:
Create a loop and display the random byte values in the array by typing the following code:
Console.WriteLine("Random Numbers:") For i = 0 To 149 Console.Write(i) Console.Write(":") Console.WriteLine(my Bytes(i)) Next i Console.WriteLine() Console.ReadKey(True)
Press "F5" to run the program.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for