-1

The following piece of code generates a IndexOutOfRangeException was unhandled, but I dont know why. The a for-loop is set to be smaller than the i for-loop because the array of arrays is 3x2. I did try to prey the i and a but with no luck. Can you see the error?

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);
            }
        }
    }
}
}

The expected output would be a .txt file :

2 3 4
5 6 7
  • `for (int i = 0; i < 4; i++)` - `i` goes from 0 to 3, array is from 0 to 2. But here's a tip: If you have problems like this, run it under the debugger and see where it breaks. – Matthew Watson Sep 16 '16 at 14:48

1 Answers1

0

loop A repeated 4 times instead of 2 times

Instead of using magic numbers use 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);
                }
Pepernoot
  • 3,409
  • 3
  • 21
  • 46