Sin*_*ján 1 c# arrays for-loop indexoutofboundsexception
我正在尝试使用数组进行用户名和密码比较,在C#中创建一个非常基本的登录系统.
我正在使用for()循环来比较用户提供的用户名和密码以及我的阵列中的用户名和密码.这是我的循环代码:
string user = null, usrpassword = null;
string[] usernames = {"admin", "guest"};
string[] userpasswords = {"adminpw", "guestpw"};
Console.Write("Username: "); //Username
user = Console.ReadLine();
Console.Write("Password: "); //Password
usrpassword = Console.ReadLine();
Console.WriteLine("Processing...");
for (int i = 0; i <= usernames.Length; i++)
{
if (user == usernames[i] && usrpassword == userpasswords[i])
{
loginloop = false;
Console.WriteLine("Login Successful.");
}
else if (i > usernames.Length)
{
//incorrect username
Console.WriteLine("Incorrect username or password!");
}
} //for-loop-end
Run Code Online (Sandbox Code Playgroud)
我在构建时没有遇到任何语法错误,但是当它到达for循环时它会崩溃并给我一个IndexOutOfRange异常.
数组索引开始在0与上去Length - 1,所以你只需要继续循环,而迭代器是小于Length.
更改<=为<:
for (int i = 0; i < usernames.Length; i++)
{
...
}
Run Code Online (Sandbox Code Playgroud)