Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2024
  • Last Modified:

Generate Random Number Within a predetermined range - VB.NET

I am trying to generate a random number in a VB .Net application but I need the number to be within a predetermined range (the range will be 0 to TotalCount).

I know this can be done, but it's been forever since I've done it and I nolonger have MSDN information files available.

If anyone has any ideas, let me know.

Thanks,

Rorc
0
Rorc
Asked:
Rorc
1 Solution
 
inq123Commented:
Hi Rorc,

Please see this page: http://www.brettb.com/RandomNumbersInDotNet.asp

Basically something like:

Dim RandomClass As New Random()
Dim RandomNumber As Integer
RandomNumber = RandomClass.Next(TotalCount)

Should do it

Cheers!
0
 
RorcAuthor Commented:
Thank you, I knew it could be done but just couldn't remember how.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Just remember that the value passed into the Next method is NOT included.  In the example below, a number between 0 and 14 inclusive will be returned:

        Dim TotalCount As Integer = 15
        Dim RandomClass As New Random
        Dim RandomNumber As Integer
        RandomNumber = RandomClass.Next(TotalCount)

Here is the Random.Next() help:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemrandomclassnexttopic3.asp

From the Return value remarks:
"A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not MaxValue. If minValue equals maxValue, minValue is returned."

This also holds true for the Next() method that acceps two parameters.  The first value will be included but the second will not:

        Dim RandomClass As New Random
        Dim RandomNumber As Integer
        RandomNumber = RandomClass.Next(4, 15)

The above will return a value between 4 and 14 inclusive.

~IM

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now