Strings-creating“passwords"和“;users"(简单的字符串)
本文关键字:quot 字符串 简单 passwords Strings-creating users | 更新日期: 2023-09-27 18:15:47
我需要创建一个程序,将采取用户名和"密码"。如果匹配,程序就会告诉你,如果不匹配,你就出局了。我为一个用户写的,但我不知道如何在一个程序中创建多个用户。我的代码如下。谢谢你的帮助:)
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();
//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();
这应该可以工作(不包含检查输入值是否正确的检查,您应该自己添加这种安全措施:)):
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();
为什么不用数组呢?
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
对于更大的列表,我建议您使用外部文本文件并在每个文件中读取行