Stack Exchange
Preventing indexoutofboundsexception in a 2d Array
just wondering what is wrong with my code. Hidden tests show that an invalid array index comes back as 'valid'.
Here is my code:
/**
 * Check if the array index is inside the grid
 * 
 * @param x - row
 * @param y - column
 * @return true if given index is inside the grid; otherwise false
 */
public boolean validIndex(int x, int y)
{
    boolean result = false;

    for (int i = 0; i < arr.length; i++)
    {
        for (int j = 0; j < arr.length; j++)
        {
            if (i >= 0 && i < arr.length && j >= 0 && j < arr.length)
            {
                result = true;
            }
        }
    }
return result;
}


I dont think this code can throw IndexOutOfBoundException on it own. Post complete code.

This seems like an inefficient way of doing it - there's no need to loop through each array to find out if the index is valid or not.

Also, given the structure of the loops, this function will always return true because both i and j will always be between 0 and arr.length

I use a nested for-loop as arr[][] holds objects.of type 'Cell'. I'm testing whether the coordinate of that particular Cell is valid or invalid

Your code is ignoring the input x and y indices and always returns true (unless the input array has 0 rows).
Check the passed indices x and y instead of having those loops.
All you need is :
if (x >= 0 && x < arr.length && y >= 0 && y < arr[x].length)
    result = true;


yes, the 2d array is a grid of size = size * size (ie: a square grid)

@Khai Still, you are ignoring the input of your validIndex method.

As soon as I can, I will accept your answer. Thank you very much for your help!!!!
