2013-05-08 39 views
-4

嗨我想做一個登錄屏幕,其中用戶將輸入用戶名和密碼。但我如何使用數組驗證它?請幫忙謝謝如何使用數組驗證用戶名和密碼

 int[] username = { 807301, 992032, 123144 ,123432}; 

     string[] password = {"Miami", "LosAngeles" ,"NewYork" ,"Dallas"}; 

     if (username[0].ToString() == password[0]) 
     { 
      MessageBox.Show("equal"); 
     } 
     else 
     { 
      MessageBox.Show("not equal"); 
     } 
+3

不應該是'if(userName == username [0] .ToString()&& password == password [0]){}',其中'userName'和'password'是用戶輸入嗎? – NINCOMPOOP 2013-05-08 05:04:59

+0

yes you correct thank you!但我如何檢查其他索引? – user1954418 2013-05-08 05:08:44

回答

0

你需要從你的陣列username先找到用戶名的索引。然後根據該索引比較密碼數組中的密碼。

int[] username = { 807301, 992032, 123144, 123432 }; 

string[] password = { "Miami", "LosAngeles", "NewYork", "Dallas" }; 

int enteredUserName = 123144; 
string enteredPassword = "NewYork"; 

//find the index from the username array 
var indexResult = username.Select((r, i) => new { Value = r, Index = i }) 
          .FirstOrDefault(r => r.Value == enteredUserName); 
if (indexResult == null) 
{ 
    Console.WriteLine("Invalid user name"); 
    return; 
} 

int indexOfUserName = indexResult.Index; 

//Compare the password from that index. 
if (indexOfUserName < password.Length && password[indexOfUserName] == enteredPassword) 
{ 
    Console.WriteLine("User authenticated"); 
} 
else 
{ 
    Console.WriteLine("Invalid password"); 
} 
0

爲什麼你不使用字典?字典是某種數組,但它將匹配的鍵和值組合在一起。 TryGetValue將嘗試查找用戶名。如果找不到用戶名,該功能將返回false,否則將返回true和匹配的密碼。該密碼可用於驗證用戶輸入的密碼。

Dictionary<int, string> userCredentials = new Dictionary<int, string> 
{ 
    {807301, "Miami"}, 
    {992032, "LosAngeles"}, 
    {123144, "NewYork"}, 
    {123432 , "Dallas"}, 
}; 

int userName = ...; 
string password = ...; 

string foundPassword; 
if (userCredentials.TryGetValue(userName, out foundPassword) && (foundPassword == password)) 
{ 
    Console.WriteLine("User authenticated"); 
} 
else 
{ 
    Console.WriteLine("Invalid password"); 
}