I have two classes, a Teacher class and a Student class. In my program I create an array of 10 Teacher objects and within each Teacher object is an array of 10 Student Objects. Each Student object also has an array of integers as a member variabe, and when each Student is instantiated, it’s own array of integers are filled with numbers from a random number generator. My program goes something like this:
- An array of type Teacher is created with size 10
- The array is then filled with 10 actual teacher objects
- Each Teacher object contains an array of Student objects of size 10 as a member variable
- The Student array in each Teacher object is filled with actual Student objects
- Each student object has an array of integers that are filled with random numbers in the Student objects constructor.
Here is the problem I ran into: It seems that every time the 10 Student objects are created for each Teacher, the random number generator within the Student object constructor does not reset or change even when I call the .Next() function until the next set of 10 Student objects are created for the next Teacher object. What I want is the 10 Teacher objects to each have their own Student Objects which have their own integer arrays filled with randomly generated numbers.
Any help would be appreciated! I ran into this sort of problem with constructors with my last question, and that was a matter of whether something was to be static or not and I’m not sure that’s the case this time. Please ask me questions if I wasn’t clear enough about anything!!
UPDATE** So after looking at MSDN, I found in their sample code “Thread.Sleep(2000)” and stuck it into my Student Constructor just to see what it did. It seemed to have solved the problem although my program runs a lot slower now, is there a minimum sleep value to wait until the Random.Next() uses a new seed from the clock and even if I did solve the problem, is there a better way to do this? My random number generator is already a static member variable of Student.
If you initialize several
Randominstances using the default constructor,Random(), within a short time period, then you risk that they would end up with the same seed value (which is time-dependant) and, therefore, generate the same random sequence each time.You can fix this issue by initializing a single static
Randominstance, and share it among allStudentinstances. This is perfectly safe as long as you’re not multi-threading.From the MSDN page on the Random() constructor:
Edit: Although you state that your random number generator is already a static member, this is still not enough if you’re instantiating it repeatedly (redundantly) during each
Studentinitialization. The following code is still incorrect:You need to replace it with a version that only instantiates
Randomonce, like so: