|
So far, we have been using any number that would fit an integer. In some assignments, you may want to restrict the range of numbers that can be extracted. Fortunately, the Random class allows this. Using the Random class, you can generate random positive numbers up to a maximum of your choice. To support this, the Random class is equipped with another version of the Next() method whose syntax is: Public Overridable Function Next(maxValue As Integer) As Integer The argument to pass to the method determines the highest integer that can be generated by the Next() method. The method returns an integer. Here is an example that generates random numbers from 0 to 20: REM Imports System
Module Exercise
Public Function Main() As Integer
Dim nbr As Integer
Dim rndNumber As Integer = 0
Dim rndNumbers As Random = New Random
For nbr = 1 To 9
rndNumber = rndNumbers.Next(20)
Console.Write("Number: ")
Console.WriteLine(rndNumber.ToString())
Next
Return 0
End Function
End Module
Here is an example of running the program: Number: 1 Number: 7 Number: 1 Number: 16 Number: 14 Number: 19 Number: 3 Number: 1 Press any key to continue . . . The above version of the Next() method generates numbers starting at 0. If you want, you can specify the minimum and the maximum range of numbers that the Next() method must work with. To support this, the Random class is equipped with one more version of this method and that takes two arguments. Its syntax is: Public Overridable Function Next(minValue As Integer, _ maxValue As Integer) As Integer The first argument specifies the lowest value that can come from the range. The second argument holds the highest value that the Next() method can generate. Therefore, the method would operate between both values. Here is an example that generates random numbers from 6 to 18: Module Exercise
Public Function Main() As Integer
Dim nbr As Integer
Dim rndNumber As Integer = 0
Dim rndNumbers As Random = New Random
For nbr = 1 To 9
rndNumber = rndNumbers.Next(6, 18)
Console.Write("Number: ")
Console.WriteLine(rndNumber.ToString())
Next
Return 0
End Function
End Module
Here is an example of running the program: Number: 17 Number: 9 Number: 8 Number: 15 Number: 10 Number: 9 Number: 13 Number: 11 Press any key to continue . . . |
|
|||
|
|