Pergunta

The code loops through the array and initialises each of the index to '*'. However I'm getting an IndexOutOfRangeException on Cave[i,j] and would like some guidance.

char[,] Cave = new char[GridHeight, GridWidth];

    for (int i = 0; i < GridWidth; i++)
    {
        for (int j = 0; j < GridHeight; j++)
        {
            Cave[i, j] = '*'; //Error Here
        }
    }
  • For clarification GridHeight, GridWidth are declared as follows

    public const int GridHeight = 5;

    public const int GridWidth = 7;

Foi útil?

Solução

You're declaring a 5 x 7 array, but then trying to access (for example) Cave[7,5] because your variables are backwards.

char[,] Cave = new char[GridHeight, GridWidth];  // declare 5x7 array

for (int i = 0; i < GridWidth; i++)        // range of i is 0 - 6
{
    for (int j = 0; j < GridHeight; j++)   // range of j is 0 - 4
    {
        Cave[i, j] = '*'; //Error Here     // try to access Cave[6,4] - oops!
    }
}

Try swapping them:

char[,] Cave = new char[GridWidth, GridHeight];

Or swap the other pair if it makes more sense to you:

char[,] Cave = new char[GridHeight, GridWidth];

for (int i = 0; i < GridHeight; i++)
{
    for (int j = 0; j < GridWidth; j++)
    {
        Cave[i, j] = '*';
    }
}

Outras dicas

Usually the way we look at things and the way the compiler does are not the same.

Here's your program output:

int GridHeight = 10;
int GridWidth = 5; 

char[,] Cave = new char[GridHeight, GridWidth];

for (int i = 0; i < GridWidth; i++)
{
   for (int j = 0; j < GridHeight; j++)
   {
        Console.Write(i+","+ j +"   ");
      // Cave[i, j] = '*'; //Error Here
   }
    Console.WriteLine();
}

It outputs:

0,0   0,1   0,2   0,3   0,4   0,5   0,6   0,7   0,8   0,9   
1,0   1,1   1,2   1,3   1,4   1,5   1,6   1,7   1,8   1,9   
2,0   2,1   2,2   2,3   2,4   2,5   2,6   2,7   2,8   2,9   
3,0   3,1   3,2   3,3   3,4   3,5   3,6   3,7   3,8   3,9   
4,0   4,1   4,2   4,3   4,4   4,5   4,6   4,7   4,8   4,9   

As you can see, the first variable is the actual width, not height. So either rename them, or swap them around :)

whenever you're thinking about a 2 dimensional array (at least console output wise), remember the the first axis is the X (left to right, ascending order) , and the second is the Y (up to down, ascending order).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top