-2

I need to create a program that will take the users name and "password". If they match the program will say you are in if not, that you're out. I wrote it for 1 user, but I don't know how to make multiple users in one program. My code is below. Thanks for your help :)

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();
4

3 回答 3

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();
于 2013-05-29T12:12:02.470 回答
1

This should work (contains no checks to see if the entered values are correct or not, you should add this kind of safety yourself :)):

        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();
于 2013-05-29T12:15:07.410 回答
-2

Why not use arrays?

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");
    }
}

This will work with the following name/pswrd combinations: James/Pass1, John/Word2, Jude/Password3

For a bigger list I suggest you use external text file and read lines in each.

于 2013-05-29T12:49:32.010 回答