【问题标题】:IndexOutOfRangeException error in C# after creating a double loop [duplicate]创建双循环后C#中的IndexOutOfRangeException错误[重复]
【发布时间】:2017-01-24 20:26:18
【问题描述】:

下面这段代码生成了一个未处理的 IndexOutOfRangeException,但我不知道为什么。 a for-loop 设置为小于i for-loop,因为数组的数组是 3x2。我确实尝试过捕食 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

【问题讨论】:

  • for (int i = 0; i &lt; 4; i++) - i 从 0 到 3,数组从 0 到 2。但是这里有一个提示:如果你有这样的问题,在调试器下运行它,看看它在哪里中断.

标签: c# arrays multidimensional-array streamwriter


【解决方案1】:

循环 A 重复 4 次而不是 2 次​​p>

不要使用幻数,而是使用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);
                }

【讨论】:

  • 您始终可以使用 Length/Count 属性来确保您的循环不会超出范围的界限。
  • 轰隆隆!哈哈。伟大的思想都一样,@CodeJoy!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
  • 2020-08-01
相关资源
最近更新 更多