Randomization+(VB)


 * This is a way to get random numbers to appear on the screen. When someone clicks on a label, a random number appears between 1 and 20.**

Public Class Form1 Dim rndRandom As New Random Private Sub lblRandom_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lblRandom.Click lblRandom.Text = rndRandom.Next(1, 20) End Sub End Class
 * Define new random object!!!**
 * Specifying that we want the label to display a random number between 1 and 20!!!!**

__ ICS2O - Randomization __

Visual Basic 2008 has included an “easier” way than ever to generate random numbers. We have talked about how you can declare variables – you can declare something to be “Random” as well.

Remember, here is an example of how to declare a simple integer variable:

· Dim intRand As Integer

We are simply declaring that we’re going to need somewhere in RAM to store an integer value.

Now, here is an example of how to declare a “Random” __OBJECT__.

· Dim rndRand As **// New //** Random

Why am I referring to an “integer __variable__”, but a “random __object__”? Because Visual Basic has data types like integer, decimal, string and so on. It also has things called CLASSES. What we are doing with the Random bit here is **__ creating a new object of the Random class __**.

Classes are different from variables because //variables simply hold values//. That’s it. Classes are more powerful because they have their own methods. This means that they are __programmed to do stuff for you__! So every “Random” object comes with a method (called Next) that will generate a random number for you and you can even define the minimum and maximum bounds.

So after I create “rndRand” (an object that is an instance of the Random class), I can use the built –in “Next” method to generate a random number between (for example) 10 and 20 as follows:

· intRandomNumber = rndRand.Next(10, 20)

The above line of code would create a random number between 10 and 20 and store that value in the variable called “intRandomNumber”.