Reputation: 11
Im creating a program that will generate a word search game but am still in the early stages. I have taken all the input from a text file and converted it into an array that provides the word, its initial row and column starting point, and whether its horizontal or vertical. I have started a new method that will create the basic puzzle array that contains only the word to be hidden. My problem is that im consistently getting:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at WordSearch.createPuzzle(WordSearch.java:50)
at WordSearch.main(WordSearch.java:25)
The snippet of code that is the issue is as follows:
public static char[][] createPuzzle(int rows, int cols, Word[] words) {
char[][] puzzle = new char[rows][cols];
for (int i = 0; i <= 9; i++) {
int xcord = words[i].getRow();
int ycord = words[i].getCol();
if (words[i].isHorizontal() == true) {
String word = words[i].getWord();
for (int j = 0; j < word.length(); j++ ) {
puzzle[xcord + j][ycord] = word.charAt(j);
}
} else {
String word = words[i].getWord();
for (int k = 0; k < word.length(); k++) {
puzzle[xcord][ycord + k] = word.charAt(k);
}
}
}
return puzzle;
}
public static void displayPuzzle(String title, char[][] puzzle) {
System.out.println("" + title);
for(int i = 0; i < puzzle.length; i++) {
for(int j = 0; j < puzzle[i].length; j++) {
System.out.print(puzzle[i][j] + " ");
}
System.out.println();
}
}
with:
displayPuzzle(title, createPuzzle(11, 26, words));
in my main method alongside the code that creates the words array.
Upvotes: 0
Views: 120
Reputation: 12205
puzzle[xcord + j][ycord] = word.charAt(j);
If xcord is 8 and j is > 1 you will get an index out of bounds error because your puzzle board only has 9 rows.
You need to make sure your words don't go past the puzzle boundaries.
Upvotes: 1