密码控制台应用程序使用while循环

问题描述 投票:0回答:4

所以基本上我正在尝试编写一个控制台应用程序,它要求用户输入密码并继续只要求它三次,然后使用'while'循环停止,但它继续循环并询问我对于密码,即使使用了正确的密码,在我输入3次之后也是如此。

const string pass = "Password";            
string attempt;

do
{
    Console.Write("Please enter password: ");
    attempt = Console.ReadLine();

    if (attempt == pass)
    {
        Console.WriteLine("Access granted.");
    }
    else
    {
        Console.WriteLine("Access denied.");
    }
} while (true);
c# while-loop passwords console-application limit
4个回答
2
投票
const string pass = "Password";            
string attempt;

int n = 0;
do
{
    Console.Write("Please enter password: ");
    attempt = Console.ReadLine();

    if (attempt == pass)
    {
        Console.WriteLine("Access granted.");
        break;
    }
    else
    {
        Console.WriteLine("Access denied.");
        n++;
    }
} while (n<=3);

1
投票

因此,您需要三次询问用户密码,直到输入正确的密码并停止询问用户是否正确输入。你可以通过for循环来做到这一点

const string pass = "Password";            
string attempt;

for(int i=0;i<3;i++)
{
    Console.Write("Please enter password: ");
    attempt = Console.ReadLine();

    if (attempt == pass)
    {
        Console.WriteLine("Access granted.");
        i = 4;
    }
    else
    {
        Console.WriteLine("Access denied.");
    }
};

0
投票

您可以执行以下操作:

const string pass = "Password";            
string attempt;
int attempt = 0;

do
{
    Console.Write("Please enter password: ");
    attempt = Console.ReadLine();

    if (attempt == pass)
    {
        Console.WriteLine("Access granted.");
    }
    else
    {
        Console.WriteLine("Access denied.");
        attempt++;
    }
} while (attempt <= 3 && attempt != pass);

0
投票
         string pass = "";

        while (pass != "password")
        {
            Console.WriteLine("enter your password here");
            pass = Convert.ToString(Console.ReadLine());
            if (pass == "password")
            {
                Console.WriteLine("your password is correct");
            }
      }
        Console.ReadKey();
© www.soinside.com 2019 - 2024. All rights reserved.