只是想知道我的代码有什么问题。隐藏测试显示无效数组索引返回为“有效”。
这是我的代码:
/**
* 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;
}
最佳答案
您的代码忽略了输入 x
和 y
索引并始终返回 true(除非输入数组有 0 行)。
检查传递的索引 x
和 y
而不是那些循环。
所有你需要的是:
if (x >= 0 && x < arr.length && y >= 0 && y < arr[x].length)
result = true;
关于java - 防止二维数组中的 indexoutofboundsexception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33146709/