小编Sin*_*ján的帖子

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

我正在尝试使用数组进行用户名和密码比较,在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异常.

c# arrays for-loop indexoutofboundsexception

1
推荐指数
1
解决办法
103
查看次数

标签 统计

arrays ×1

c# ×1

for-loop ×1

indexoutofboundsexception ×1