Random numbers can be generated by the Visual Basic Rnd() function, that returns a floating-point value between 0.0 and 1.0. Multiplying the random numbers will specify a wider range. For example, a multiplier of 20 will create a random number between zero and 20. To make the generated random number more useful, you can round it up to the nearest higher integer value with the Math.Ceiling() method so the range, in this case, becomes from 1 to 20.
The numbers generated by Rnd() are not truly random, but are merely a sequence of pseudo random numbers produced by an algorithm from a specific starting point. Whenever an application loads, a call to the Rnd() function will begin at the same starting point – so the same sequence will be repeated. This is not generally desirable, so the application needs to create a new starting point when it loads to avoid repetition. This can be achieved by calling the Randomize() function in the Form’s Load event, to “seed” the Rnd() function with a starting point based upon the system time when the application gets loaded – now the sequence of generated numbers is different each time.
Add a Label, TextBox, and Button control to a Form, and arrange them like this:
Name the Label control Msg, set its AutoSize property to False, then assign the text illustrated above to its Text property
Name the TextBox control Guess, and set the Text property of the Button likewise
The numbers generated by the algorithm for Randomize() and Rnd() may be predicted, so this technique should not be used for cryptography.
Click on View, Code to open the Code Editor, then create a variable in the Declarations
Dim num As Integer
Still in the declarations section, add a Sub routine to assign a random number 1-20 to the num variable
Private Sub GetNumber()
____num = Math.Ceiling( Rnd() * 20 )
In the Form’s Load event-handler, add a call to seed the random number generator and a call to set the num variable with an initial pseudo random value
Now, add some logic to the Button control’s Click event-handler with this code
Select Case ( Val( Guess.Text) )
Case Is > num
Msg.text = Guess.Text & “ is too high”
Case Is < num
Msg.Text = Guess.Text & “ is too low”
Case Is = num
Msg.Text = Guess.Text & “ is correct” & _
“I have thought of another number – Try again!”
Guess.Text = “”
Run the application and guess the random number
The integer value must be extracted from the TextBox by the Val() function before making any comparison.
Want to know more?
For the complete Visual Basic guide covering Visual Studio Community 2015, all in the trusted In Easy Steps style, click here. In full-colour and straightforward, jargon-free language, Visual Basic in easy steps, 4th edition shows you how to quickly create Windows applications using the latest free programming environment. This book gives you code examples, screenshots, and step-by-step instructions that illustrate each aspect of Visual Basic.