dimanche 6 mars 2022

C# | How to make goto statements when not in scope

I'm currently working on a little lottery game in a console window made with C#.

I added a feature that lets the user randomize the 6 numbers he will have on his ticket but noticed that my random number generator sometimes generates the same number even tho you can theoratically only have a number once, so I built this check to see if any number is the same only to notice that I cant go back to randomizing a new list of numbers because the goto function cant go out of a loop (CS0159). Any other way to do this?

Code:

                Console.WriteLine("\nRandomized 6 numbers: ");
                
                // Randomize 6 numbers in for the array randomList
                for (int z = 0; z <= 5; z++)
                {
                SameNum:
                    int rndNum = rnd.Next(1, 50);
                    randomList[z] = rndNum;
                }
                // Once the list is done check if any elements of the array
                // are the same and if yes go back to SameNum to generate a new 
                // List of 6 numbers
                for (int a = 0; a <= 5; a++)
                {
                    for (int b = 0; b <= 5; b++)
                    {
                        while (randomList[a] == randomList[b])
                        {
                            goto SameNum;
                        }
                    }

                }

                // Display the random list if there are no same numbers
                for (int c = 0; c <= 5; c++)
                {
                    Console.WriteLine(randomList[c] + " ");
                }



Aucun commentaire:

Enregistrer un commentaire