如果形状在给定的 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;
}
最佳答案
您需要检查row
或col
是否小于零,或者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/