如何检查2D数组是否超出范围?

时间:2015-04-22 21:09:16

标签: java arrays

如果形状在给定isFilledAt()位置具有填充块,则true方法返回row/col,如果块为空,则返回false。如果该位置超出界限,请提出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;
    }

2 个答案:

答案 0 :(得分:3)

您需要检查rowcol是否小于零,或row是否大于或等于height,或{{1}大于或等于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

答案 1 :(得分:1)

您应该按如下方式更改isFilledAt方法

public boolean isFilledAt(int row, int col) 
{
    char[][] tempArray = new char[height][width];
    // Calls the method that fills tempArray datas

    if ( (row >= height || row <0)  || (col >= width || col < 0)) {
         throw new FitItException("Out of Bounds!");
    }

    for(int i = 0; i < height; i++)
        for(int j = 0; j < width; j++)
        {
                if(tempArray[row][col] == dc)
                return true;
        }


   }
   return false;
}

您将返回false放在错误的位置:如果查找的值不在第一行内,它会系统地返回false。而是在迭代每一行后返回false

相关问题