Start New Discussion within our Software Development Community

hello guys, i have this code written down to print a magic square and i get an error.

 public void doMagic()
    {
        int k = 1;
        int row = 0;
        int col = order/2;
        msArray[row][col] = k;

        for ( int r = 0; r < msArray.length; r++)
        {
            for ( int c = 0; c < msArray[r].length; c++)
            {
                k = k + 1;
                if (k > (order*order))
                {
                    return;
                }
                row = row - 1;
                col = col + 1;

                if (row == -1 && col == order)
                {
                    row = 1;
                    col = order - 1;
                }
                else if (row == -1)
                {
                    r = order - 1;
                }
                else if (c == order)
                {
                    c = 0;
                }
               [B][U] if (msArray[row][col] != 0)[/U][/B] <--but i get this msg here : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
                {
                    col = col - 1;
                    row = row + 2;
                }
                else
                {
                    msArray[row][col] = k;
                }
            }
        }
    }

any help would be great. thx.
i've attached a file for more info on Magic Square.

Well, it looks to me like the error is here:

col = col - 1;

if col is 0 then col-1 = -1 and the array doesn't have a column at -1, hence the outOfBounds error.

This article has been dead for over six months. Start a new discussion instead.