Results 1 to 5 of 5

Thread: generate random number from range

  1. #1

    Thread Starter
    Banned
    Join Date
    Mar 2009
    Posts
    764

    generate random number from range

    Code:
    Dim random As New Random()
    random.Next(65, 91) ' random.Next(min, max) the range is min to max -1
    EDIT for akhileshbc : place this code in an event, the Dim random As New Random() can also be placed as a global variable (in a class and not in an event )
    the code returns a random number between a minimum and a maximun in the example above a number between 65 and 91 will be returned

    you can also do stuff like : (instead of the line random.Next(65, 91))

    label1.text = random.Next(65, 91) ' the label will display a random number in the range 65 - 91
    or
    textbox1.text &= random.Next(65, 91) ' concates a random number to the textbox (added from the tool box to the form)
    or
    textbox1.text &= chr(random.Next(65, 91)) ' concates a random char (a - z) to the textbox
    Last edited by moti barski; Jul 27th, 2011 at 03:25 PM.

  2. #2
    VB For Fun Edgemeal's Avatar
    Join Date
    Sep 2006
    Location
    WindowFromPoint
    Posts
    4,255

    Re: generate random number from range

    You should clarify what this code actually returns.
    I'd bet most new coders would expect this to return a random number between 65 to 90 but it doesn't.

    Random.Next Method (Int32, Int32)
    The range of return values includes minValue but not maxValue.

  3. #3

    Thread Starter
    Banned
    Join Date
    Mar 2009
    Posts
    764

    Re: generate random number from range

    Quote Originally Posted by Edgemeal View Post
    You should clarify what this code actually returns.
    I'd bet most new coders would expect this to return a random number between 65 to 90 but it doesn't.

    Random.Next Method (Int32, Int32)
    The range of return values includes minValue but not maxValue.
    the code was tested and worked on vb.net 2010

  4. #4
    VB For Fun Edgemeal's Avatar
    Join Date
    Sep 2006
    Location
    WindowFromPoint
    Posts
    4,255

    Re: generate random number from range

    Quote Originally Posted by moti barski View Post
    label1.text = random.Next(65, 90) ' the label will display a random number in the range 65 - 90
    That call will never return 90, I already posted a link to the doc and the reason.

  5. #5

    Thread Starter
    Banned
    Join Date
    Mar 2009
    Posts
    764

    Re: generate random number from range

    post #1 edited, thanks Edgemeal

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width