我需要创建一个带有用户名和“密码”的程序。如果他们匹配该程序将说你在,如果没有,你就出去了。我是为一个用户写的,但我不知道如何在一个程序中创建多个用户。我的代码如下。谢谢你的帮助:)
Console.WriteLine("Enter your Name");
Console.WriteLine("Enter your Pswrd");
string name = Console.ReadLine();
string pswrd = Console.ReadLine();
string myname = "John";
string mypswrd = "123456";
if (name == myname & pswrd == mypswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
Console.ReadLine();
答案 0 :(得分:3)
//building the user "database" each pair is <user,password>
Dictionary<string, string> users = new Dictionary<string, string>();
users.Add("John", "123456");
//Here you should add more users in the same way...
//But i would advise reading them from out side the code (SQL database for example).
Console.Writeline("Enter your Name");
string name = Console.ReadLine();
Console.WriteLine("Enter your Passward");
string password = Console.ReadLine();
if (users.ContainsKey(name) && users[name] == password)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or password");
}
Console.ReadLine();
答案 1 :(得分:1)
这应该有效(不包含检查输入的值是否正确,你应该自己添加这种安全性:)):
Dictionary<string, string> namesToCheck = new Dictionary<string, string>
{
{"John", "123456"},
{"Harry", "someotherpassword"}
};
Console.WriteLine("Enter your Name");
string name = Console.ReadLine();
Console.WriteLine("Enter your Pswrd");
string pswrd = Console.ReadLine();
if (namesToCheck.ContainsKey(name) && namesToCheck[name] == pswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
Console.ReadLine();
答案 2 :(得分:-2)
为什么不使用数组?
Console.WriteLine("Enter your Name");
Console.WriteLine("Enter your Pswrd");
string name = Console.ReadLine();
string pswrd = Console.ReadLine();
string[] names = "James,John,Jude".Split(Convert.ToChar(","));
string[] passes = "Pass1, Word2, Password3".Split(Convert.ToChar(","));
for (int i = 0; i<names.Length, i++)
{
if (names[i] == name && passes[i] == pswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
}
这将使用以下名称/ pswrd组合: James / Pass1,John / Word2,Jude / Password3
对于更大的列表,我建议您使用外部文本文件并在每个文件中读取行。