【问题标题】:C# code worked until added final step in loop, now new is overriding old code.C# 代码一直有效,直到在循环中添加了最后一步,现在新代码覆盖了旧代码。
【发布时间】:2014-04-14 02:42:40
【问题描述】:

我在视觉工作室制作一个随机抽奖程序。它应该像这样工作:用户输入 3 个数字,然后点击按钮。然后程序生成 3 个随机数(最多)1000 次,并在列表框中显示随机生成的数字。如果用户号码是按顺序生成的,它会在尝试任何号码时停止并说“成功!在“x”次尝试后”

如果随机数在1000次后与用户数不匹配,则会弹出消息“尝试1000次后未找到匹配”

该程序一直有效,直到我到达最后一步。我添加了这段代码:

    //  -keep track of the matching status of each digit in a boolean

            bool theyMatch = (random1 == userEntered1stDigit) && (random2 == userEntered2ndDigit) && (random3 == userEntered3rdDigit);

            //check all three boolean match variables, if they are all true then we have a match to the winning number, exit out of the while
            if (theyMatch)
            {
                MessageBox.Show("Success! Match found for all 3 digits. It took " + myAttemptsInt + " tries.");
                break;
            }
            else
            {
                //add what happened to the event log
                MessageBox.Show("No match found after " + myAttemptsInt + " tries.");
                return;
            }

现在当我运行它时,它会在尝试 #1 处停止并给出成功或失败消息。新代码覆盖旧代码我错过了什么?

这就是全部内容:

     public Form1()
    {
        InitializeComponent();
    }

    //DECLARE CLASS LEVEL FIELD VARIABLES
    int CONST_cashPayoutPick3 = 500;
    int CONST_cashPayoutPick4 = 5000;
    int CONST_cashPayoutPick5 = 50000;

    private void myBtnGenRandomNumbers_Click(object sender, EventArgs e)
    {
        //DECLARE LOCAL VARIABLES
        int userEntered1stDigit = 0;
        int userEntered2ndDigit = 0;
        int userEntered3rdDigit = 0;


        //INPUT-VALIDATION
        //winning number: validate the 1st digit to be numeric, if not display error message and return
        if (int.TryParse(myTxtBox1stDigit.Text, out userEntered1stDigit))
        {
            //ok
        }
        else
        {
            MessageBox.Show("Please enter a number in the first box");
            return;
        }
        //winning number: validate the 2nd digit to be numeric, if not display error message and return
        if (int.TryParse(myTxtBox2ndDigit.Text, out userEntered2ndDigit))
        {
            //ok
        }
        else
        {
            MessageBox.Show("Please enter a number in the second box");
            return;
        }
        //winning number: validate the 3rd digit to be numeric, if not display error message and return
        if (int.TryParse(myTxtBox3rdDigit.Text, out userEntered3rdDigit))
        {
            //ok
        }
        else
        {
            MessageBox.Show("Please enter a number in the third box");
            return;
        }


        //INITIALIZE ANY VARIABLES
        userEntered1stDigit = int.Parse(myTxtBox1stDigit.Text);
        userEntered2ndDigit = int.Parse(myTxtBox2ndDigit.Text);
        userEntered3rdDigit = int.Parse(myTxtBox3rdDigit.Text);

        //GOOD SO FAR

        //PROCESSING
        //setup your own Random number generator object
        int random1 = 0;
        int random2 = 0;
        int random3 = 0;

        Random myRandomNumberObject = new Random();
        int matchNum1;
        int matchNum2;
        int matchNum3;

        //clear the list box
        myListBoxResults.Items.Clear();

        //set number of attempts = 0
        int myAttemptsInt;
        myAttemptsInt = 0;


        //LOOP THROUGH AND CREATE SETS OF 3 RANDOM DIGITS EACH TIME THROUGH LOOP UNTIL A MATCH IS FOUND OR TRY 1,000 TIMES
        while (myAttemptsInt <= 1000) 
        {

            if (myAttemptsInt <= 999)
            {
                //ok
            }
            else
            {
                break;
            }

            //get next random digit generated from 0 to 9, for your generated digit position 1
            random1 = myRandomNumberObject.Next(10);
            //get next random digit generated from 0 to 9, for your generated digit position 2
            random2 = myRandomNumberObject.Next(10);
            //get next random digit generated from 0 to 9, for your generated digit position 3
            random3 = myRandomNumberObject.Next(10);


            //display the number of match attempts so far

            //attempt # originally went here
            myAttemptsInt = myAttemptsInt + 1;

            int index = myListBoxResults.Items.Add("Attempt # " + myAttemptsInt);

            //display the generated digit 1,2,3 in the labels on the Form
            matchNum1 = random1;
            myLabelGenerated1stDigit.Text = matchNum1.ToString();
            matchNum2 = random2;
            myLabelGenerated2ndDigit.Text = matchNum2.ToString();
            matchNum3 = random3;
            myLabelGenerated3rdDigit.Text = matchNum3.ToString();

            //set the Label BackColor of all the generated digits to Color.LightGray
            myLabelGenerated1stDigit.BackColor= Color.LightGray;
            myLabelGenerated2ndDigit.BackColor = Color.LightGray;
            myLabelGenerated3rdDigit.BackColor = Color.LightGray;

            //for any generated digit that matches the winning digit,
            if (random1 == userEntered1stDigit)
            {
                myLabelGenerated1stDigit.BackColor = Color.LightGreen;
            }
            if (random2 == userEntered2ndDigit)
            {
                myLabelGenerated2ndDigit.BackColor = Color.LightGreen;
            }
            if (random3 == userEntered3rdDigit)
            {
                myLabelGenerated3rdDigit.BackColor = Color.LightGreen;
            }

            //  -keep track of the matching status of each digit in a boolean

            bool theyMatch = (random1 == userEntered1stDigit) && (random2 == userEntered2ndDigit) && (random3 == userEntered3rdDigit);

            //check all three boolean match variables, if they are all true then we have a match to the winning number, exit out of the while
            if (theyMatch)
            {
                MessageBox.Show("Success! Match found for all 3 digits. It took " + myAttemptsInt + " tries.");
                break;
            }
            else
            {
                //add what happened to the event log
                MessageBox.Show("No match found after " + myAttemptsInt + " tries.");
                return;
            }

        } 

【问题讨论】:

    标签: c# loops


    【解决方案1】:

    您正在返回而不检查循环是否已被消耗 把else去掉放到while外面,也把break改成return

    //...
    
        if (theyMatch)
        {
            MessageBox.Show("Success! Match found for all 3 digits. It took " + myAttemptsInt + " tries.");
            return;
        }
    
    }
    
    MessageBox.Show("No match found after " + myAttemptsInt + " tries.");
    

    【讨论】:

    • 我将 break 改为 return,但我很难移动东西。他希望最后一条语句结束“while”循环。所以我需要说“如果我们有匹配,结束循环”“如果我们没有匹配,继续”重新阅读说明,两个 messagebox.shows 都在循环之后,所以到底是什么结束了吗?
    • 这些是他的确切指令: if (??) { //将发生的事情添加到事件日志中 //break out of while loop since found a match break; // } else { //将发生的事情添加到事件日志中 //不需要跳出循环;继续循环}
    • 不,循环将结束,因为你已经放了“while (myAttemptsInt
    • 好的,看看你的新评论,如果你想这样做,第二次返回必须完全删除,并且每个循环都会显示一个消息框。使用消息框会很痛苦,但是如果您登录到文件/文本框,这是有道理的,您将有 X 行显示“此迭代不匹配”,还有一个显示“找到匹配”或“1000 次迭代后未找到匹配”
    • 我现在看到了,我将整个块移到了循环之后,它可以工作了。如果他打算让它在里面,那就没有多大意义了,哈哈。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 2017-01-24
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    相关资源
    最近更新 更多