0

I need help in trying to generate a random number because with my coding below it shows the same number in both text boxes.

   private int RandomNumber(int min, int max)
{

    Random random = new Random();
    random.Next();
    return random.Next(1, 7); // random integer and assigned to number  
} 


private void button1_Click(object sender, EventArgs e)
{


    tb1.Text = RandomNumber(1, 7).ToString(); // Random Number for Text Box 1.
    tb2.Text = RandomNumber(7, 1).ToString(); // Random Number for Text Box 2.

}
3
  • Random Class Commented Sep 17, 2014 at 21:55
  • Not related to your reported issue, but you have 1, 7 hardcoded in your RandomNumber routine. Also you have 7, 1 coded in one of your calls to this routine; which is probably the wrong way round given the parameter names. Commented Sep 17, 2014 at 21:56
  • possible duplicate of Same random numbers every loop iteration Commented Sep 17, 2014 at 21:56

3 Answers 3

3

Random picks a seed based on the current time.
If you create two Randoms at the same time, they will give you the same numbers.

Instead, you need to create a single Random instance and store it in a field in your class.

However, beware that Random is not thread-safe.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for explain the issue. is this applied to Java too?
@KickButtowski: In Java, you should use ThreadLocalRandom.instance(), which takes care of everything for you.
1

You need to instantiate your Random class only once. From MSDN, the documentation states that:

If the same seed is used for separate Random objects, they will generate the same series of random numbers.

In your case, as SLaKs also said, the seed is the current time. You're calling the functions so close together they are using the same seed. If you move the instantiation outside of the function, you have one instance based on one seed, instead of multiple objects based on the same seed.

Random random = new Random();

private int RandomNumber(int min, int max)
{
    return random.Next(1, 7); // random integer and assigned to number  
} 

Comments

0

You need to create the Random object outside of your function. Creating a new one each time you need a new random number will result in the seed being identical (given the time gap between creations)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.