First, your loop condition should use <
rather than <=
.
Second, if you think about the spiral you'll realize that you always end with a right movement. You hit the break
at the first time you have
if(number==endNumber)break;
but this doesn't exit you out of the while
loop - this only leaves the for
loop. So then you go into the down movement for
loop and get the index out of bounds exception.
Third, you need to first enter the center number before the loop.
Additionally, rightmovement
, leftmovement
, ... should all be increased by 2 each time. The reason for this is easier to see in a larger grid.
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
Notice the first right movement writes 2
, then the next one writes 8 9 10
, and the last one writes 22 23 24 25
and would have written 26
if you were to continue.
To fix the issue with break
not leaving the while
loop, just change it into a return
statement.