I get the error below when I try to run the application I am sure its something simple but I dont see it. What I am trying to do it when I click a button I have labeled Play. I
Setup one Random
object and initialize it once.
class Form1
{
...
Random rnd = new Random();
}
then to use it every time it is needed
void RandomNumber(int min, int max)
{
int num = rnd.Next(min, max);
...
}
What happens everytime you call new() it re-seeds the random number and you may end up with the same numbers over and over. I have had this happend to me and it killed me
Well, your code doesn't match the error, but look at this:
private void btnPlay_Click(object sender, EventArgs e)
{
RandomNumber();
}
private void RandomNumber(int min, int max)
{
int num = new Random().Next(min, max);
lblPickFive_1.Text = num.ToString();
}
RandomNumber
has two parameters, min
and max
. You haven't specified any in the call inside btnPlay_Click
. That's what the compiler is complaining about. Change the call to something like:
RandomNumber(5, 10);
Even when that's fixed, you shouldn't create a new instance of Random
each time. As it happens, it's unlikely to cause problems in this particular case as it's triggered by a user action, but you should read my article on random numbers to see what the problem is and how to avoid it.
You need to pass in values:
private void btnPlay_Click(object sender, EventArgs e)
{
RandomNumber();
}
should be:
private void btnPlay_Click(object sender, EventArgs e)
{
RandomNumber(0, 50000);
}
First, you shouldn't be newing up a random number generator every time you want a new random number. You should set the generator as a static or member variable and refer to it for each new number.
Second, you have to pass a min and a max to your RandomNumber
method.
You're calling RandomNumber();
in btnPlay_Click
but the RandomNumber
method requires min
and max
.
Your RandomNumber
method takes two arguments.
If you want to call the method, you need to pass two arguments.