Question Please help randomly generated number

Ryker Wells

Member
Joined
Feb 9, 2012
Messages
16
Location
Fort Kent, ME
Programming Experience
1-3
So I'm brand spankin' new to VB and so far am slowly understanding. But I've finally run across a problem i can't seem to find the answer to.

I'm working with a random number that generates a price for a house between 1 and 100 dollars (obviously very realistic).

VB.NET:
Dim Housecost As Integer = (Int((100 * Rnd()) + 1))

My problem is that I put that number in the public class which does generate the number but only once. But i need the number to be re-generated every time a button is clicked. Now I would put this code snippet in the buttons Sub but there are 3 other subs in the code that call for that randomly generated number and the only way that I know of that allows all the subs to read this random number is to put it in the public class.

So how do I put the number in a place where all Subs can read it and can be called to re-generate when needed?

Thank you for your time and effort!

If you need any more info I'm glad to elaborate further.
 
Seriously, I'm sick to death of teachers and text books that keep on showing new .NET programmers dodgy VB6 ways of doing things. Random numbers are a prime example. So many teachers and authors of tutorials and books have VB6 experience and they just keep on doing things the VB6 way even when VB.NET provides better options. Sorry to maybe confuse you by contradicting what you have learned but DO NOT EVER use the Rnd function. It is a holdover from VB6 and exists only to help smooth the upgrade of VB6 code to VB.NET. It should NEVER, EVER be used in new VB.NET code. In VB.NET, use the Random class. Create an instance and, to get a random Integer, call its Next method:
Dim rng As New Random
Dim num As Integer = rng.Next(1, 101)
A further point to note is that you should generally only create one instance and call its Next method multiple times, rather than creating multiple instances and calling Next once each.

Now, with regards to your question, the solution is that you should be generating the random number and storing it in a variable, then using it ONLY from that variable. If you need to use the value multiple times then you get it multiple times from that variable, only generating a new value when you need a new value. There are numerous ways that you could implement this. Here's just one:
Dim rng as New Random
Dim price As Integer

Public Function GetPrice(Optional ByVal generateNew As Boolean = False) As Integer
    If price = 0 OrElse generateNew Then
        price = rng.Next(1, 101)
    End If

    Return price
End Function
You can then get the existing price by calling GetPrice() or GetPrice(False) and you can get a new price by calling GetPrice(True).
 
Back
Top