mercredi 20 septembre 2017

Random Generator throwing same results [duplicate]

This question already has an answer here:

I came across a weired issue: When having created a form in C# to assign randomized numbers to textBox-fields I always get the same numbers returned. I.e.

1 1
1 1
1 1
1 1

The crazy thing about it is the following: When debugging it I get different numbers. Here is the source code:

namespace BlaBla
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = homeGame().ToString();
            textBox2.Text = awayGame().ToString();

            textBox3.Text = homeGame().ToString();
            textBox4.Text = awayGame().ToString();

            textBox5.Text = homeGame().ToString();
            textBox6.Text = awayGame().ToString();

            textBox7.Text = homeGame().ToString();
            textBox8.Text = awayGame().ToString();

        }

        private int homeGame()
        {
            int homeGoal = 0;
            Random rdHome = new Random();
            int homeNumber = rdHome.Next(0, 72);

            if (homeNumber < 10)
            {
                homeGoal = 0;
            }
            if (homeNumber > 10 && homeNumber < 36)
            {
                homeGoal = 1;
            }
            if (homeNumber > 35 && homeNumber < 56)
            {
                homeGoal = 2;
            }
            if (homeNumber > 55 && homeNumber < 71)
            {
                homeGoal = 3;
            }
            if (homeNumber > 70)
            {
                homeGoal = 4;
            }
            return homeGoal;
        }

        private int awayGame()
        {
            int awayGoal = 0;
            Random rdAway = new Random();
            int awayNumber = rdAway.Next(0, 700);

            if (awayNumber < 100)
            {
                awayGoal = 0;
            }
            if (awayNumber > 100 && awayNumber < 411)
            {
                awayGoal = 1;
            }
            if (awayNumber > 410 && awayNumber < 506)
            {
                awayGoal = 2;
            }
            if (awayNumber > 505 && awayNumber < 661)
            {
                awayGoal = 3;
            }
            if (awayNumber > 660)
            {
                awayGoal = 4;
            }
            return awayGoal;
        }

    }
}

I know, this code is not the best in the world. However does someone have an idea what is wrong here? Respectively what would be the corrected code please?




Aucun commentaire:

Enregistrer un commentaire