C# 将int变量用作数组选择器时发生IndexOutfrange异常
我正在尝试用C#创建一个非常基本的登录系统,使用数组比较用户名和密码 我使用C# 将int变量用作数组选择器时发生IndexOutfrange异常,c#,arrays,for-loop,indexoutofboundsexception,C#,Arrays,For Loop,Indexoutofboundsexception,我正在尝试用C#创建一个非常基本的登录系统,使用数组比较用户名和密码 我使用for()循环将用户提供的用户名和密码与数组中的用户名和密码进行比较。以下是我的循环代码: string user = null, usrpassword = null; string[] usernames = {"admin", "guest"}; string[] userpasswords = {"adminpw", "guestpw"}; Console.Write("Username: "); //User
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
string user=null,usrpassword=null;
字符串[]用户名={“admin”,“guest”};
字符串[]userpasswords={“adminpw”,“guestpw”};
控制台。写入(“用户名:”//用户名
user=Console.ReadLine();
控制台。写入(“密码:”)//密码
usrpassword=Console.ReadLine();
Console.WriteLine(“处理…”);
for(int i=0;i usernames.Length)
{
//不正确的用户名
Console.WriteLine(“不正确的用户名或密码!”);
}
}//用于循环结束
我在构建时没有收到任何语法错误,但是当它到达for循环时,它会崩溃,并给我一个
indexoutfrange
异常。数组索引从0
开始,上升到Length-1
,因此您只想在迭代器小于Length
时继续循环
更改
数组索引从0
开始,并上升到Length-1
,因此您只希望在迭代器小于Length
时继续循环
更改您的for条件循环中只有一个“off by one”样式的错误
for(int i=0;i在for循环条件中,您只是有一个“off by one”样式的错误
用于(int i=0;i你真的想依靠两个不同集合的索引来查找用户的密码吗?你至少可以使用字典来代替。用户名是密钥,密码是值。你真的想依靠两个不同集合的索引来查找用户的密码吗?你至少可以不要改用词典
。用户名是密钥,密码是值。@SindriKristján,如果其中一篇帖子回答了你的问题,你应该这样标记。这样,其他有类似问题的用户会更容易看到这些答案。@SindriKristján,如果其中一篇帖子回答了你的问题,你应该将其标记为这样,其他有类似问题的用户将更容易看到这些答案。
for (int i = 0; i < usernames.Length; i++)
{
...
}