防止二维数组中的 indexoutofboundsexception

Preventing indexoutofboundsexception in a 2d Array

只是想知道我的代码有什么问题。隐藏测试显示无效数组索引返回为 'valid'.

这是我的代码:

/**
 * 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;
}

您的代码忽略了输入 xy 索引并且始终 returns 为真(除非输入数组有 0 行)。

检查传递的索引 xy 而不是那些循环。

您只需要:

if (x >= 0 && x < arr.length && y >= 0 && y < arr[x].length)
    result = true;