简单的 C# 登录尝试 3 次

Simple C# login with 3 attempts

我需要创建一个简单的 C# Sharp 程序,它将用户 ID 和密码作为输入(字符串类型)。在 3 次错误尝试后,用户应该被拒绝。

我已经开始了,但我不确定应该如何正确地完成逻辑。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UserId
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Type username");
            String UserId1 = Console.ReadLine();
            Console.WriteLine("Type password");
            String Pass = Console.ReadLine();

            String UserIdCorrect = "test1";
            String PassCorrect = "password1";
            int MaxAttempts = 3;



            Console.ReadKey();

            if (UserId1 != UserIdCorrect && Pass != PassCorrect ) {
                MaxAttempts++;

            }


            Console.ReadKey();

        }
    }
}

我猜你是初学者。我已经评论了代码。

int maxAttempts = 3;

// looping n (maxAttempts) times
for(int i = 0; i < maxAttempts; i++)
{
    // get input and check it
}

// do what ever you want here.
// at least show up a message

多种方式。正如 HebeleHododo 评论的那样,您还可以使用 while 循环并使用 if-else 检查是否达到了 maxAttempts。

只需 运行 for 循环 3 次,如果仍然用户输入错误的条目而不是禁用 window。

首先,甚至在编写一行代码之前,尝试花一两分钟考虑命名约定。这就像 "putting foam on your face before having a shave. You can get a shave even without the shaving foam but the experience wouldn't be nice"。试试这个 link 了解更多信息 [https://msdn.microsoft.com/en-us/library/ms229045(v=vs.110).aspx]

现在进入你的问题,如果我只需要满足你的要求,这段代码就足够了。在这里,我将 "valid" 作为正确凭据的标识符:

<code>
    //Login Attempts counter
    int loginAttempts = 0;

    //Simple iteration upto three times
    for (int i = 0; i < 3; i++)
    {
        Console.WriteLine("Enter username");
        string username = Console.ReadLine();
        Console.WriteLine("Enter password");
        string password = Console.ReadLine();

        if (username != "valid" || password != "valid")
            loginAttempts++;
        else
            break;
    }

    //Display the result
    if (loginAttempts > 2)
        Console.WriteLine("Login failure");
    else
        Console.WriteLine("Login successful");

    Console.ReadKey();
</code>