0

I am working on a project for a intro VB class. I need to create a random number between 2 values the user enters. I have an upper limit textbox/variable and a lower limit textbox/variable. I have tried everything I could find and it produces weird results. I can't figure out how to get the random numbers generated between 2 values. For example if the user enters 100 for the lower limit and 500 for the upper limit the random should be in the range of 100-500.

Please let me know what I am doing wrong??

'Grabs the txbox input and assigns to vars
intLowNumber = CInt(mskLowerRange.Text)
intUpperNumber = CInt(mskUpperRange.Text)

intRandomNumber = rand.Next(intUpperNumber) - intLowNumber

'Output to listbox and textbox
lstOutput.Items.Add(intRandomNumber)
txtNumber.Text = CStr(intRandomNumber)
Brian Smith
  • 57
  • 1
  • 3
  • 11

1 Answers1

4

Your code is wrong, specifically

intRandomNumber = rand.Next(intUpperNumber) - intLowNumber

Say intUpperNumber is 200 and intLowNumber is 100, the above gives somewhere between -100 (0 - 100) and 99 (199 - 100).

You can give Random.Next two parameters for a random number in a range. The first parameter is the minimum value and the second parameter is the maximum value of the random number.

Note that the upper bound (the maximum value) is exclusive, so if you want to include the highest value you need to add 1. Use it like this:

'Grabs the txbox input and assigns to vars
intLowNumber = CInt(mskLowerRange.Text)
intUpperNumber = CInt(mskUpperRange.Text)

intRandomNumber = rand.Next(intLowNumber, intUpperNumber+1)

'Output to listbox and textbox
lstOutput.Items.Add(intRandomNumber)
txtNumber.Text = CStr(intRandomNumber)
Thorkil Holm-Jacobsen
  • 7,287
  • 5
  • 30
  • 43
  • Can you please explain how I would use that in my code? I went to the link but I still cant' figure out how to use that in my code. Sorry please bare with me I am a beginner and just learning VB. – Brian Smith Nov 24 '13 at 09:59
  • Thank you sir that explained it perfectly. I am very new to VB and I didn't get that the MSDN page was telling me to put it in the format rand.Next(lower, upper) Looking at the MSDN website it looked like it was written on 4 lines I didn't understand that it was all one line until you showed me. Thanks again you made my night :) – Brian Smith Nov 24 '13 at 10:12
  • @Code_Help: No problem, glad I could help :) There is usually a lot of help to get from the MSDN pages. A lot of the articles have examples at the end in C# and VB. – Thorkil Holm-Jacobsen Nov 24 '13 at 10:42