2015-04-22 121 views
2

方法isFilledAt()返回true如果该形状在给定的row/col位置上具有填充块,并且如果该块为空,则该形状具有false。如果位置超出范围,请提供带有信息性消息的FitItException。我正在运行一个嵌套循环来获得位置,并且很难找出一个位置是否超出范围。可以帮忙吗?提前致谢!如何检查二维数组是否超出范围?

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; 
    } 
+0

'isFilledAt'应该做什么?当然'tempArray'应该是一个实例变量,并且该方法应该测试其中的一个条目?目前'tempArray'是一个局部变量,所以你对它做出的改变都会丢失。 –

回答

3

您需要检查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。将系统返回false如果抬头值不是第一行内:

+0

谢谢! @AndersonVieira – Nikolay

+0

@尼科莱很高兴帮助!虽然这应该解决“越界”问题。在你的代码中,似乎还有一些关于'tempArray'的东西。你应该考虑关于它的pbabcdefp评论。 –

+0

你是什么意思tempArray中有什么关闭?这些循环有没有错? @AndersonVieira – Nikolay

1

如下

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; 
} 

你把你的回报在错误的地点错误,您应该改变你的isFilledAt方法。取而代之的是,在每一行迭代后都返回false