0

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.

2
  • which is line 50? are you sure your words has 10 items? Commented Apr 8, 2016 at 19:03
  • Line 50 is puzzle[xcord + j][ycord] = word.charAt(j); My words array has exactly 10 items Commented Apr 8, 2016 at 19:07

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.