1

您好,我是 C# 新手,我想制作一个简单的 C# 密码程序,用户只能输入 3 次或尝试输入 3 次密码,程序将使用 Application.Exit() 退出;

但似乎循环使 MessageBox 一直很烦人,并且不允许用户在接下来的 2 次尝试中按下或键入按钮。

请帮助我吗?

用这个编辑但是“使用'pin'的未命名局部变量”的错误T_T:

private int _failedAttempts = 0;


    private void btnEtr_Click(object sender, System.EventArgs e)
    {
        int pin;

        if (pin != 21)
        {
            if (pin !=21)
            {
                _failedAttempts++;
                MessageBox.Show ("Fail. " + (3 - _failedAttempts) + " attempts more.", "EPIC FAIL", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                if(_failedAttempts == 3)
                {                       
                    Application.Exit();
                }
            }

        }

        else
        {
            MessageBox.Show ("Welcome. Your pin is CORRECT", "CONGRATULATIONS",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }
    }
4

3 回答 3

4

现在你基本上是在告诉用户他们失败了,减少计数器,然后告诉他们他们又失败了。

您没有给他们重新输入密码的机会。您需要跟踪按钮单击事件之外的尝试。声明一个将跟踪尝试的类级别变量。

例如

private int _failedAttempts = 0;

并将您的按钮单击更改为:

if (pin !=21)
{
  _failedAttempts++;
  MessageBox.Show ("Fail. " + (3 - _failedAttempts) + " attempts more.", "EPIC FAIL", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

   if(_failedAttempts == 3)
   {                       
     Application.Exit();
   }
}

这让用户输入密码,如果失败,它将显示错误消息并增加尝试次数。你应该让他们再次输入密码,然后让他们再次按下回车键。当它达到 3 次尝试时,它将退出。

于 2011-03-10T21:48:53.500 回答
1

您可能想在事件之外使用变量

private int attemptsLeft = 3;

private void btnEtr_Click(object sender, System.EventArgs e)
    {
        int pin = Convert.ToInt32(txtbox.Text);             

        if (pin !=21)
        {

                MessageBox.Show ("Fail. " + --attemptsLeft  + " attempts more.", "EPIC FAIL", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

              if( attemptsLeft == 0 )
              {
                   Application.Exit();
              }
        }
        else
        {
            MessageBox.Show ("Welcome. Your pin is CORRECT", "CONGRATULATIONS",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
于 2011-03-10T21:50:17.867 回答
0

那是因为您正确使用了 for 循环。即使他们只尝试了一次,您也正在循环 3 次尝试。尝试这个:

整数计数器 = 0;

private void btnEtr_Click(object sender, System.EventArgs e) { int pin; 诠释我;

    pin = Convert.ToInt32(txtbox.Text);             

    if (pin !=21)
    {
        MessageBox.Show ("Fail. " + counter.toString() + " attempts more.", "EPIC FAIL",                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        counter += 1;

        if (counter = 3)
            {                       
                Application.Exit();
            }
    }

    else
    {
        MessageBox.Show ("Welcome. Your pin is CORRECT", "CONGRATULATIONS",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
}

这样,您就可以计算该人按下按钮的次数。确保您的计数器在您的主要方法中,以便记录您的尝试

于 2011-03-10T21:49:32.063 回答