954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

MagicSquare Number

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;
}
if (msArray[row][col] != 0) <--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.

Attachments Asg3MagicSquare.pdf (95.07KB)
Taimoor Rana
Light Poster
47 posts since Feb 2010
Reputation Points: 10
Solved Threads: 2
 

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.

litchi
Light Poster
32 posts since Aug 2008
Reputation Points: 10
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: