java - 防止二维数组中的 indexoutofboundsexception

标签 java arrays indexoutofboundsexception

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

这是我的代码:

/**
 * 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 索引并始终返回 true(除非输入数组有 0 行)。

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

所有你需要的是:

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

关于java - 防止二维数组中的 indexoutofboundsexception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33146709/

相关文章:

c++ - 为什么 std::vector::at() 即使启用了优化也需要边界检查?

Android:传递值时出现 ArrayIndexOutOfBoundsException

java - 如何在 Mule ESB 中持久化包含 Java 消息的队列?

java - new File(filename) 对象的创建是否将进程文件描述符与该对象相关联?

java - 标记界面的目的是什么?

arrays - 如何在 Kotlin 中将 String 数组转换为 Int 数组?

android - simple_list_item_checked 中的 ArrayIndexOutOfBoundException 错误

C++ system() 调用未正确记录 Java 返回码

javascript - 在javascript中将数组本身合并到另一个具有相同键的数组中

c - 如何将 uint8_t 数组从 C 发送到 GO