如果不满足条件,则重复操作特定次数

Repeating action specific number of times if condition is not met

我正在尝试制作一个具有密码访问权限的控制台应用程序,设法编写代码来询问密码,但我希望它重复询问密码(如果错误)4 次,但不是永远,我试着用 for 循环来做,但没有用,有人能告诉我问题出在哪里吗?

 class Password
    {
        public static bool verifyPassword()
        {
            bool loginSuccess1;
            Console.WriteLine("enter password");
            string userInput = Console.ReadLine();
            string password = "12";
            loginSuccess1 = (userInput == password);
            return loginSuccess1;

        }
        public static void checkPassword()
        {
            bool loginSuccess;
            int loginCount = 1;
            loginSuccess = verifyPassword();
            while (!loginSuccess && loginCount < 5)
            {

                verifyPassword();
                if (!loginSuccess)
                    loginCount++;
            }
            if (loginSuccess)
            {
                Console.WriteLine("correct answer");
            }

        }
    }
    class Program
    {

        static void Main(string[] args)
        {
            Password.checkPassword();
        }
    }

如果密码不正确,调用wrongPassword。然后调用 verifyPassword 4 次(正如您所怀疑的那样),除非您再次 错误 ,它会再次调用 wrongPassword,从而调用 verifyPassword再四次...你明白了。

我会有 verifyPassword return 一个布尔值(如果它成功了),而不是调用 wrongPassword (只是删除那个函数)然后只有一个新函数:

bool loginSuccess;
int loginCount = 1;

while (!loginSuccess && loginCount < 5)
{
    loginSuccess = VerifyPassword();

    if (!loginSuccess)
        loginCount++;
}

现在你没有递归循环,它只会检查 4 次。