Kip Verslaafde
Kip Verslaafde

Reputation: 153

Create random numbers for sums

I need to create random numbers but the numbers arent random in the labels 2 are random but all the sums are the same:

Here is my code

int input = int.Parse(txt1.Text);
    if (input <= 6)
    {
        int Getal1 = 0;
        int Getal2 = 0;
        Random generator = new Random();
        for (int x = 0; x < 11; x++)
        {
            Getal1 = generator.Next(input) + 1;
            Getal2 = generator.Next(input) + 1;
            Getal1.ToString();
            Getal2.ToString();
        }
        //int Getal2 = generator.Next(input) + 1;
        //int Getal3 = generator.Next(input) + 1;
        //int Getal4 = generator.Next(input) + 1;
        //int Getal5 = generator.Next(input) + 1;
        //int Getal6 = generator.Next(input) + 1;
        //int Getal7 = generator.Next(input) + 1;
        //int Getal8 = generator.Next(input) + 1;
        //int Getal9 = generator.Next(input) + 1;
        //int Getal10 = generator.Next(input) + 1;


        lbl1.Text = Getal1.ToString();
        lbl2.Text = Getal2.ToString();
        lbl3.Text = Getal1.ToString();
        lbl4.Text = Getal2.ToString();
        lbl5.Text = Getal1.ToString();
        lbl6.Text = Getal2.ToString();
        lbl7.Text = Getal1.ToString();
        lbl8.Text = Getal2.ToString();
        lbl9.Text = Getal1.ToString();
        lbl10.Text = Getal2.ToString();

It does work when i remove the loop and undo the commentary. But that is so much code i think i can do it smaller.

Upvotes: 1

Views: 139

Answers (2)

filhit
filhit

Reputation: 2154

You should move Random generator = new Random(); and all the variable declarations outside the loop. You can also put all the labels into an array, so you don't have to assign each separately. Also you've assigned the label's text only to the latest Getal1, Getal2 values. That's why only all other pairs got the same value as the first one.

int input = int.Parse(txt1.Text);
if (input <= 6)
{
    Random generator = new Random();
    Label[] labels = new [] {
        lbl1,
        lbl2,
        lbl3,
        lbl4,
        lbl5,
        lbl6,
        lbl7,
        lbl8,
        lbl9,
        lbl10
    };

    for (int x = 0; x < labels.Length; x++)
    {
        labels[x].Text = (generator.Next(1, input)).ToString();
    }

    error.Text = "";
    pnl1.Visible = true;
}

The default Random constructor initializes the random seed to a value based on the current time.

Upvotes: 4

DespeiL
DespeiL

Reputation: 1033

    int input = int.Parse(txt1.Text);   
     Random r = new Random();
                    List<int> sums = new List<int>();
                    if(input<=8)
                    {

                        for (int i = 0; i <= 10; i++)
                        {
                            sums.Add( r.Next(input)+ r.Next(input));
                        }
 lbl1.Text = sums[0].ToString();
                    }

Upvotes: 0

Related Questions