C# C# Collections Arrays Jagged Arrays

Dominik Huber
Dominik Huber
4,631 Points

On my implementation I get this error: Object reference not set to an instance of an object - please help me.

Hi guys,

attached is my approach to solve this problem. Unfortunately not that successfully :D

I get this error in the title. I rubberducked this thing and all makes sense in my head but it's still throwing that error. What does it mean? I hate that I can't see what the compiler tells me exactly, can't figure out what exactly went wrong.

Could you please help me guys :) ?

/edit: I figured out that I never instantiate the 2nd array in the "array". I added this code line in the first for loop:

multTable[i] = new int[maxFactor];

But now I get another error:

The table should contain 6 rows and 6 columns

What is going on?

Math.cs
namespace Treehouse.CodeChallenges
{
    public static class MathHelpers
    {
        public static int[][] BuildMultiplicationTable(int maxFactor)
        {
            int[][] multTable = new int[maxFactor][];
            for(int i = 0; i < maxFactor; i++)
            {
              multTable[i] = new int[maxFactor];
              for (int j = 0; j < maxFactor; j++)
              {
                  multTable[i][j] = (i * j);

              }
            }
            return multTable;
        }
    }
}

2 Answers

Steven Parker
Steven Parker
172,046 Points

You can see complier errors using the "Preview" button, but the original code compiled OK and produced run-time errors when tested.

Now you may also need to adjust the table size and loop limits. Remember that you want the table to include maxFactor, not stop just short of it.

Dominik Huber
Dominik Huber
4,631 Points

Wow that was fast.

I edited my question tough. Maybe you can take a quick 2nd look on the question please? :) I don't know why it's not working. At least I get no errors now :D

Edit: I think you edited your answer too? I don't know how exactly you mean this "not stop just short of it" ? I include it do I? Because the array has a size of maxFactor and I loop through the whole array.

Maybe you can explain this to me in more details ? :) Thx man always appreciate it!

Steven Parker
Steven Parker
172,046 Points

If your loop condition is "i < maxFactor" the loop will run for values up to, but not including maxFactor. Similarly, when sizing an array, the largest possible index will be less than the number of elements, since the index values begin at 0.

Dominik Huber
Dominik Huber
4,631 Points

Ok I see. Thank you very much. Could fix it with maxFactor + 1 in the array creation and i <= maxFactor in the loop(s).

Steven Parker
Steven Parker
172,046 Points

It sounds like you have the right idea, why not try it and see?

And happy coding!