This is from my attempt at the knights tour game, and what I was trying to do here was show the user what moves they could make from whatever position they are in, in the array.
The problem arrives with NextPos[x+1][y-2]!=null
in the if statement, as the exception java.lang.ArrayIndexOutOfBoundsException: -2
is thrown.
I know the array is out of bounds at this position, but that was the point, so that it would not print that this position was available.
My question is, is there a way to get the same result* or to catch the exception so it passes?
*To use the out of bounds array in the if().
The array looks like this when printed:
1 2 3 4 A{0 0 0 0} B{0 0 0 0} C{0 0 0 0}
The values for x
and y
are 0
. The Board array is the same size as the NextPos array, but it is an int array.
public static void MoveTo(int x, int y, int Board[][]) { TextIO.putln("jhgkgk"); String NextPos[][] = { {"A1", "A2", "A3", "A4"}, {"B1", "B2", "B3", "B4"}, {"C1", "C2", "C3", "C4"} }; for (int i = 0; i < 9; i++) { switch (i) { case 1: if (NextPos[x + 1][y - 2] != null && Board[x + 1][y - 2] == 0) { TextIO.putln("test to see if the code gets this far :3"); TextIO.putln(NextPos[x + 1][y - 2]); } break; case 2: if (NextPos[x + 1][y + 2] != null && Board[x + 1][y + 2] == 0) { TextIO.putln(NextPos[x + 1][y + 2]); } break; case 3: if (NextPos[x + 2][y - 1] != null && Board[x + 2][y - 1] == 0) { TextIO.putln(NextPos[x + 2][y - 1]); } break; case 4: if (NextPos[x + 2][y + 1] != null && Board[x + 2][y + 1] == 0) { TextIO.putln(NextPos[x + 2][y + 1]); } break; case 5: if (NextPos[x - 1][y - 2] != null && Board[x - 1][y - 2] == 0) { TextIO.putln(NextPos[x - 1][y + 2]); } break; case 6: if (NextPos[x - 1][y + 2] != null && Board[x - 1][y + 2] == 0) { TextIO.putln(NextPos[x + 1][y + 2]); } break; case 7: if (NextPos[x - 2][y + 1] != null && Board[x - 2][y + 1] == 0) { TextIO.putln(NextPos[x - 2][y + 1]); } break; case 8: if (NextPos[x - 2][y + 1] != null && Board[x - 2][y + 1] == 0) { TextIO.putln(NextPos[x - 2][y + 1]); } break; } } }
Advertisement
Answer
First of all, you are getting indexOutOfBound, still you want to skip step. You can figure and fix it. AFA your question is concerned, here is a quick fix for you.
Add the check
(y-2>0)
With
NextPos[x+1][y-2]!=null
So change your if condition to
(y-2>0) && NextPos[x+1][y-2]!=null