首页 > 解决方案 > 我需要程序停止询问用户名和密码是否正常

问题描述

我已经创建了这个用户 ID 和密码控制台应用程序。首先,我询问并确认他们输入了一个 ID 整数而不是字符串。接下来,我要求输入密码;如果用户 ID 和密码匹配我添加到应用程序以验证的预定值,它会登录用户。显然效果很好,但如果用户和密码第一次正常,而不是停止,它会继续询问 ID 名称和密码,我试过break,还是不行。谢谢。

using System;

namespace UserId
{
    class Program
    {
        static void Main(string[] args)
        {
            string text;
            var username = 123;
            string password = "valid";

            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("Please,Enter your user ID number :");
                text = Console.ReadLine();

                if (!int.TryParse(text, out username))
                {
                    Console.WriteLine("Please, Enter a valid ID number such as a 12345");
                }
                else
                {
                    Console.WriteLine("Please enter your password:");
                    password = Console.ReadLine();
                }

                if (username == 123 && password != "valid")
                {
                    Console.WriteLine("Incorrect user ID and password combination, Try again");
                }
            }

            if (username == 123 && password == "valid")
            {
                Console.WriteLine("You are now logged in!");
                Console.ReadLine();
            }
        }
    }
}

这是问题的屏幕截图:

在此处输入图像描述

标签: c#passwords

解决方案


只需将您的代码更改为此。它将检查用户名或密码是否不正确它会提示错误,否则它将登录并且不会第二次询问

if (username != 123 || password != "valid")
{
   Console.WriteLine("Incorrect user ID and password combination, Try again");
}

else
{
    break;
}


推荐阅读