Search code examples
javamultidimensional-arrayindexoutofboundsexception

Comparing three indices in a multidimensional array in java resulting in an out-of-bounds exception


I'm currently making a tic-tac-toe game using multidimensional arrays in java, and I seem to have hit a wall here. I'm comparing three indices to find out if they're the same (to declare a winner). I've found that I can successfully compare two with no exceptions thrown. However, if I compare three, an out of bounds exception is thrown after displaying that the user has won (horizontally). I'm really unsure of what's going on. The array is 5-by-5 and is of type String, with all values initially set to " ". I'm pretty illiterate with this website, so I'm sorry if the question was formatted improperly!! Please let me know so that I can improve! :) Code:

for (int row = 0; row < testArray.length; row++)
        {
            for (int column = 0; column < testArray[row].length; column++)
            {
                if ((testArray[row][column].equals("x")) && (testArray[row][column + 2].equals("x")) && (testArray[row][column + 4].equals("x")))
                    System.out.println("You win!");

                if (!(column % 2 == 0))
                    testArray[row][column] = "|";

                else if (!(row % 2 == 0))
                    testArray[row][column] = "-";

                System.out.print(testArray[row][column]);
            }
            System.out.println("");
        }

Thank you so so much in advance!

Edit: For reference, I'm typing row = 0, column = 0. r=0 col=0 is then set to x. An iteration happens, r=0, col=2 is set to x, and then it asks again. When I get to r=0, col=4 is when the exception happens.


Solution

  • In this line you cannot use:

    ((testArray[row][column].equals("x"))  
       &&(testArray[row][column + 2].equals("x")) 
       && (testArray[row][column + 4].equals("x"))
    

    For columns greater than 3 it will throw an IndexOutOfBoundException. So you should have that 2 and 4 as variables and adjust according to the for loop.