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

本文关键字:IndexOutOfRange 异常 选择器 数组 int 变量 使用 | 更新日期: 2023-09-27 18:35:04

我正在尝试使用数组在 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异常。

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

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

<=更改为<

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

您的 for 循环条件中只有一个"关闭一"样式错误;

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

应该改为

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

数组是"零索引",其中 Length 属性是从 1 到 n 计数的长度。最终索引实际上是小于 Length 的值,如果是空数组,则为 0。