c#中创建双循环后的IndexOutOfRangeException错误
本文关键字:IndexOutOfRangeException 错误 双循环 创建 | 更新日期: 2023-09-27 18:07:13
下面的代码段生成了一个未处理的IndexOutOfRangeException,但我不知道为什么。因为数组的数组是3x2,所以a for-loop
被设置为小于i for-loop
。我确实试过捕食I和a,但运气不好。你能看到错误吗?
namespace text_test
{
class txt_program
{
// () You don't use "args" in the method
public void txt()
{
int[][] names = { new int[] { 2, 3, 4}, new int[] { 5, 6, 7} };
using (StreamWriter SW = new StreamWriter(@"txt.txt"))
{
for (int i = 0; i < 4; i++)
{
for (int a = 0; a < 3; a++)
{
SW.Write(" " + names[i][a]);
}
SW.WriteLine(names);
}
}
}
}
}
预期的输出将是一个.txt文件:
2 3 4
5 6 7
循环A重复4次而不是2次
用GetLength()
for (int i = 0; i < names.GetLength(0); i++)
{
for (int a = 0; a < names.GetLength(1); a++)
{
SW.Write(" " + names[i][a]);
}
SW.WriteLine(names);
}