PDA

Click to See Complete Forum and Search --> : csharp for looping


merhaba
Sep 8th, 2007, 02:37 PM
I am tring to assign random numbers to each 4 label .on my form.but I got stuck..:mad: would you pls fix it ?




private void timer1_Tick(object sender, EventArgs e)
{
Random RandomClass = new Random();

for (int a = 1; a <= 4; a++)
{
int rn(a) = RandomClass.Next(1, 20);
lb(a).Left = lb(a).Left + rn;
}
}







Thanks

jmcilhinney
Sep 8th, 2007, 08:08 PM
Maybe it would be a good idea if you were to explain exactly what you're trying to achieve with your code rather than just posting the code and asking us to fix it. If we don't know what exactly it's supposed to do then how can we make it do it? Please consider this when posting in future.

First of all, you wouldn't create a new Random object each time. You should create one Random object and assign it to a member variable, then use it every time.

Now, can I confirm exactly what you're trying to do there? It looks like you're trying to move each Label in the horizontal direction, where the amount you move it is a random value from 1 to 20. Is that correct? If so it should look like this:private Random rnd = new Random();

private void timer1_Tick(object sender, EventArgs e)
{
foreach (Label lbl in this.labels)
{
lbl.Left += rnd.Next(1, 21);
}
}Note that that will keep moving the Labels to the right, so before long they're going to disappear off the right edge of the form.

Note also that the maximum value returned by the Next method is always less than the value you specify, so if you want 20 to be a possible result then you have to specify 21 as the maximum.