我遇到的问题是,当循环到达第二条if
语句时,它崩溃了(“索引在数组的边界之外。”)。我只需要在循环的最后一个数字上跳过它。我该如何解决?我尝试添加&&
,但我想这是错误的。
for (int i = Count; i <= words1.Length; i++)
{
if (i == words1.Length)
{
for (int bb = Count3; bb < words2.Length; bb++)
{
sw.Write($" {words2[bb]}");
}
sw.Write(" >>> End of file 2 >>> ");
//break; // don't need that to break.
}
if (words1[i] == words2[Count]) // Statement that crashes.
{
<Lots of code>
}
else
{
sw.Write($"{words1[i]} ");
if (i == words1.Length)
{
sw.Write(" >>> End of file 1 >>> ");
}
c = false;
}
}
答案 0 :(得分:1)
为避免使用index out of bounds error
,您可以结合使用if(i == words1.Length)
语句(因为我认为这是您一直在做的事情)。
for (int i = Count; i <= words1.Length; i++)
{
if (i == words1.Length)
{
for (int bb = Count3; bb < words2.Length; bb++)
{
sw.Write($" {words2[bb]}");
}
sw.Write(" >>> End of file 2 >>> "); // You've parsed through all words2
sw.Write(" >>> End of file 1 >>> "); // since `i=Length` you've parsed
//through all words1 now too
break;
}
if (words1[i] == words2[Count]) // Statement that crashes.
{
<Lots of code>
}
else
{
sw.Write($"{words1[i]} ");
c = false;
}
}
我认为这可以保留您想要的所有逻辑,并且不会崩溃。
原因是您不应该在第二条if
语句中做这个“绑”:
i == words1.Length
,则第二条if
语句将崩溃,并显示“索引超出范围”错误。i == words1.Length
,sw.Write($"{words1[i]} ");
将失败,并出现相同的错误。为什么我建议的方法有效?
words1
将打印出从words1[Count]
到words1[words1.Length-1]
的所有单词。如果words1[i] == words2[Count]
<Lots of code>
将执行。然后,当您到达words1.Length
时,将遍历words2
。 if
为1时,您要做的第二条i == words1.Length
语句将打印出最后一个单词(已完成且没有Out of Bounds
错误),并且2)输入“> >>文件结尾1 >>>“。您完成了我的建议。<Lots of code>
超出范围时,您将永远无法执行i == words1.Length
(因为没有words1[words1.Length]
,它不存在)。您也不能写words1[i]
(同样,它不存在)。希望这是有道理的。