MessageBox.Show简单的“登录尝试”问题

时间:2011-03-10 21:42:50

标签: c# login-attempts

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

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

请帮助我吗?

使用此编辑但是“使用'无效的局部变量''''错误”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);

        }
    }

3 个答案:

答案 0 :(得分:4)

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

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

e.g。

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次尝试时它将退出。

答案 1 :(得分: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);
        }
    }

答案 2 :(得分:0)

这是因为你正确使用了你的for循环。即使他们只试过一次,你也会循环3次尝试。试试这个:

int counter = 0;

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

    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);
    }
}

通过这种方式,您可以计算此人按下按钮的次数。确保您的计数器在主方法中,以便记录您的尝试

相关问题