Visual Studio的C#彩票循环程序

时间:2018-11-06 23:27:34

标签: c# visual-studio loops random boolean

我目前正试图找出如何在Visual Studio中创建一个程序的方法,该程序与文本框中给出的3个数字1-9相匹配,在列表框中具有3个随机生成的数字。我在弄清楚如何编写WHILE循环语句时遇到麻烦,该语句允许我的列表框一次随机生成3个数字,如果没有匹配项,则继续,但是如果有匹配项,则中断,最多尝试1000次。我对如何执行此操作有些迷茫。谢谢您的帮助。

        private void LuckyButton_Click(object sender, EventArgs e)
    {
        Random RandomNumber = new Random();
        string newLine = Environment.NewLine;
        int Winning1 = 0;
        int Winning2 = 0;
        int Winning3 = 0;
        int numbers = RandomNumber.Next(10);

        int.TryParse(WinningNumber1.Text, out Winning1);
        int.TryParse(WinningNumber2.Text, out Winning2);
        int.TryParse(WinningNumber3.Text, out Winning3);


        if (Winning1 <= 0 || Winning2 <= 0 || Winning3 <= 0)
        {
            MessageBox.Show("Enter a number!");
            return;
        }

        while (numbers <= 1000)
        {
            numbers = RandomNumber.Next(10);
        }

    }

1 个答案:

答案 0 :(得分:0)

看看这是否对您有帮助:

 private void LuckyButton_Click(object sender, EventArgs e)
    {
        Random RandomNumberGenerator = new Random();
        string newLine = Environment.NewLine;
        int Winning1 = 0;
        int Winning2 = 0;
        int Winning3 = 0;
        int randomNumber = RandomNumberGenerator.Next(10);
        int counter = 0;
        int winnerId = 0;


        int.TryParse(WinningNumber1.Text, out Winning1);
        int.TryParse(WinningNumber2.Text, out Winning2);
        int.TryParse(WinningNumber3.Text, out Winning3);


        if (Winning1 <= 0 || Winning2 <= 0 || Winning3 <= 0 ||
            Winning1 > 10 || Winning2 > 10 || Winning3 > 10)
        {
            MessageBox.Show("Invalid Number!");
            return;
        }

        while (counter < 1000)
        {
            if (Winning1 == randomNumber)
            {
                winnerId = 1;
                break;
            }
            else if (Winning2 == randomNumber)
            {
                winnerId = 2;
                break;
            }
            else if (Winning3 == randomNumber)
            {
                winnerId = 3;
                break;
            }
            randomNumber = RandomNumberGenerator.Next(10);
            counter++;
        }

        if(winnerId != 0)
        {
            MessageBox.Show("Number " + winnerId + " wins!");
        }
        else
        {
            MessageBox.Show("no one wins!");
        }
    }