Frage

I got a function that generates a random number (0-97), and I've made it so it never repeats the numbers.

But my application crashes when all numbers have been used instead of displaying a MessageBox. Any help ?

"#" means that the number was already chosen.

Function for random number:

    private int RandomJeton()
    {
        int i, ok = 0;
        for (i = 0; i <= 97; i++)
            if (!Sac[i].Equals("#")) ok = 1;
        if (ok == 1)
        {
            Random r = new Random();
            int poz = r.Next(0, 97);
            while (String.Equals(Sac[poz], "#"))
                poz = r.Next(0, 97);
            return poz;
        }
        else return 101;
    }

Function that uses the random number generator:

   private void button_RClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            int x = RandomJeton();
            if (x == 101) { MessageBox.Show("Ai ramas fara jetoane", "Oops!"); ((Button)sender).Visible = false; }
            else
            {
                ((Button)sender).Text = Sac[x];
                Sac[x] = "#";
            }
        }
        copySuportCaBackup();
    }
War es hilfreich?

Lösung

Your problem is, the maximum number of random is exclusive.So in this loop:

for (i = 0; i <= 97; i++)

You are iterating over until the Sac[97], but you never assign a value to Sac[97] because you never return 97 from your function.r.Next(0, 97); will return 96 max.So your while loop never ends after all of your items become equal to #. You need to change r.Next(0, 97); to r.Next(0, 98); or i <= 97; to i < 97;

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top