List 比较两个不同列表中的元素时出现问题
我目前正在尝试创建一个打字测试程序。我在比较这两个列表中的元素列表1(10个随机单词)和列表2(10个用户输入)时遇到问题。下面是我收到的错误消息:List 比较两个不同列表中的元素时出现问题,list,arguments,compare,elements,outofrangeexception,List,Arguments,Compare,Elements,Outofrangeexception,我目前正在尝试创建一个打字测试程序。我在比较这两个列表中的元素列表1(10个随机单词)和列表2(10个用户输入)时遇到问题。下面是我收到的错误消息:ArgumentOutOfRangeException未处理 我不知道为什么,但当我进入debug菜单时,它会将列表1的值显示为Count=1,而列表2的值显示为Count=10。两个列表中的所有元素都是字符串。因此,我的问题是如何按顺序比较这些列表中的元素(第一个列表的第一个元素与第二个列表的第一个元素),依此类推 我对编码比较陌生,我不明白为什么
ArgumentOutOfRangeException未处理
我不知道为什么,但当我进入debug菜单时,它会将列表1的值显示为Count=1
,而列表2的值显示为Count=10
。两个列表中的所有元素都是字符串。因此,我的问题是如何按顺序比较这些列表中的元素(第一个列表的第一个元素与第二个列表的第一个元素),依此类推
我对编码比较陌生,我不明白为什么下面的代码不起作用。我已经试着修复了几个小时,所以提前感谢您的帮助
`for (int i = 0; i < gameLength; i++) // The code below will loop 10 times
{
List<string> list1 = new List<string>();
string chosenWord = SelectWord(); // Selects a random word
Console.Write(chosenWord + " "); // Prints the selected word
list1.Add(chosenWord); // Adds the selected word to the list
if (i == 9) // True once above code has been performed 10 times
{
Console.WriteLine();
List<string> list2 = new List<string>();
for (int b = 0; b < 10; b++) // This will also loop 10 times
{
string userValue = UserInput(); // Gets user input
list2.Add(userValue); // Adds user value to list
}
for (int t = 0; t < 10; t++)
{
if (list1[t] == list2[t]) // Here is the error
{
score++;
Console.WriteLine(score);
/* The error occurs on the second pass
* when the value of t becomes 1, But i don't
*/ understand why that doesn't work.
}
}
}
}`
`for(inti=0;i
尝试声明列表1=new List()
在第一个for
循环之外,我认为您的问题是因为您每次都声明list1
,所以最后list1
的迭代计数只有1,因为每次都创建了新的循环
我认为这就是问题所在
根据你的立场,我会这样做:
List<string> list1 = new List<string>();
for (int i = 0; i < gameLength; i++) // The code below will loop 10 times
{
string chosenWord = SelectWord(); // Selects a random word
Console.Write(chosenWord + " "); // Prints the selected word
list1.Add(chosenWord); // Adds the selected word to the list
}
List<string> list2 = new List<string>();
for (int b = 0; b < 10; b++) // This will also loop 10 times
{
string userValue = UserInput(); // Gets user input
list2.Add(userValue); // Adds user value to list
}
int score = 0;
for (int t = 0; t < 10; t++)
{
if (list1[t] == list2[t]) // Now should work
{
score++;
}
}
Console.WriteLine(score);
List list1=新列表();
对于(inti=0;i
@David你说得对!非常感谢你的帮助!我真的很感激。也许只是一句话。在比较字符串时,您应该小心,因为字符串是和对象。我建议您使用.Equals()