java - 如何检查二维数组是否越界?

标签 java arrays

如果形状在给定的 row/col 位置有填充 block ,则方法 isFilledAt() 返回 true返回 false 如果 block 是空的。如果位置超出范围,则引发带有信息性消息的 FitItException。我运行一个嵌套循环来获取位置,但无法确定位置是否超出范围。 smb可以帮忙吗?提前致谢!

public class CreateShape {

    private int height;
    private int width;
    private char dc;
    private Rotation initialPos;


    public CreateShape(int height, int width, char dc)
    {
        this.height = height;
        this.width = width;
        this.dc = dc;
        initialPos = Rotation.CW0;
    }
public boolean isFilledAt(int row, int col) 
    {
        char[][] tempArray = new char[height][width];
        for(int i = 0; i < tempArray.length; i++)
            for(int j = 0; j < tempArray[i].length; j++)
            {
                if(row > tempArray.length || row < 0)
                    throw new FitItException("Out of Bounds!");

                if(tempArray[row][col] == dc)
                    return true;
            }

        return false;
    }

最佳答案

您需要检查rowcol是否小于零,或者row是否大于或等于 >height,或者如果col大于或等于width。请注意,您只需要进行一次验证,因此您可以将检查移到循环之外:

public boolean isFilledAt(int row, int col)  {
    if (row < 0 || row >= height || col < 0 || col >= width) {
        throw new FitItException("Out of Bounds!");
    }
    char[][] tempArray = new char[height][width];
    for (int i = 0; i < tempArray.length; i++) {
        for (int j = 0; j < tempArray[i].length; j++) {
            if (tempArray[row][col] == dc) {
                return true;
            }
        }
    }
    return false;
}

但请注意,isFilledAt() 可能无法按您的预期工作。由于每次调用该方法时都会重新创建 tempArray,因此条件 tempArray[row][col] == dc 可能永远不会计算为 true .

关于java - 如何检查二维数组是否越界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29808883/

相关文章:

c - C 编程中数组大小分配错误?

javascript - 循环遍历对象数组并返回这些对象的累积数据

java - 将小十六进制字符串转换为整数

java - 将 java List<Double> 传递给 dart List<double> 时出错

java - 应该计算数组中所有对的代码无法正常工作

java - Spark - 使用 OpenCSV 解析文件的序列化问题

javascript - 通过在javascript中传递键和值从数组中获取对象

javascript - 如何在alert中打印数组数据

java - 查找数组中以特定数字开头的数字

java - @Before、@BeforeClass、@BeforeEach 和 @BeforeAll 之间的区别