使用int变量作为数组选择器时的IndexOutOfRange异常

时间:2013-10-10 22:14:59

标签: 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

构建时我没有遇到任何语法错误,但是当它到达for循环时,它会崩溃并给我一个IndexOutOfRange异常。

2 个答案:

答案 0 :(得分:5)

数组索引从0开始,一直到Length - 1,所以你只想在迭代器小于Length时继续循环。

<=更改为<

for (int i = 0; i < usernames.Length; i++)
{
    ...
}

答案 1 :(得分:1)

你的for循环条件中只有一个“off by one”样式错误;

for (int i = 0; i <= usernames.Length; i++)

应该是

for (int i = 0; i < usernames.Length; i++)

数组是“零索引”,其中Length属性是从1到n的长度。最终索引实际上是一个小于Length的值,或者在空数组的情况下为0。