登录系统C#//显示结果问题

时间:2019-03-21 12:27:33

标签: c#

    static void Main(string[] args)
    {
        //Login attempt
        int loginAttempts = 0;

        //3 chance login system
        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine("Enter Username");
            string userid = Console.ReadLine();
            Console.WriteLine("Enter password");
            String password = Console.ReadLine();


            if (userid != "Daniel" || password != "polle")
                loginAttempts++;
            else
                break; //Maybe "return"?
        }

        //Show result
        if (loginAttempts > 3)
            Console.WriteLine("Login failure");
        else
            Console.WriteLine("Login succesfull");

        Console.ReadLine();




    }

我没有让我的显示结果功能正常工作,当我运行程序时,它仅在3次尝试后就退出了,我该如何做些什么才能使其显示结果?谢谢

2 个答案:

答案 0 :(得分:1)

问题出在您的if (loginAttempts >= 3) 条件上。您需要

>=

注意用>代替String符号

答案 1 :(得分:0)

提取方法,然后是return

    private static bool TryLogin(int attempts = 3) {
      // Try attempts times
      for (int i = 0; i < attempts; ++i) {
        Console.WriteLine("Enter Username");
        string userid = Console.ReadLine();

        Console.WriteLine("Enter password");
        string password = Console.ReadLine();

        // if both userid and password are correct return true - login succeed - true
        if (userid == "Daniel" && password == "polle")            
          return true;
      }

      // all attempts are exhausted, login failed - false
      return false; 
    }

然后使用它:

    static void Main(string[] args) {
      if (!TryLogin()) {
        Console.WriteLine("Login failure");

        return;
      }

      Console.WriteLine("Login successful"); 

      //TODO: user logged on, put relevant code here 
    }