IndexOutOfBounds异常处理

时间:2015-03-26 01:30:40

标签: java indexoutofboundsexception

我正在做一个需要计算位置(x,y)周围像素的NxN平均值的作业。

当我传入一个大小变量时,我试图制作一个能够做到这一点的通用函数。

我只允许尺寸或NxN矩阵为3x3,5x5或7x7。

我想要做的是为每个像素制作一些通用循环,它会检查它是否是一个角落情况,然后是一个侧面案例,如果不是其中任何一个是默认情况。

实施例

0  1  2  3  4
5  6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24

如果我想要进行5x5平均值,则需要这25个像素值进行计算。但如果我的(x,y)位置在(1,2),它将超出界限。

我试图弄清楚每个场景的情况,但我发现它很难解决,因为有些情况出现了5x5而3x3并不存在。 如果我的(x,y)位于(1,1)它不会落在我的角落情况下,但它确实属于我的两个侧面情况(顶部和左侧)。

我想知道将所有内容都放入try catch语句是否安全/值得,如果数组位置超出界限,那就没什么大不了的。

我根本不需要做任何案例,如果他们超出范围,我可以检查9(3x3),25(5x5)或49(7x7)个别数组位置。

前3x3

try{
      imageBuffer.getRBG(x - 1, y -1);
 }catch{...}
try{
      imageBuffer.getRBG(x, y -1);
 }catch{...}
try{
      imageBuffer.getRBG(x + 1, y -1);
 }catch{...}

这看起来真的很糟糕,但我试图弄清楚这些案例是否适用于任何平均值的一般函数。

如果像素(x,y)周围的NxN平均值超出范围,它将计算边界中像素的平均值。如果它是3x3平均值并且它是第一个角落情况(左上角为(0,0)),我将计算我可以访问的4个像素。 所以

0 1 2
3 4 5
6 7 8

我会计算4,5,7和8的平均值

1 个答案:

答案 0 :(得分:3)

不,如果没有必要,不要引发异常。这是编码风格的问题。在这种情况下,解决方案实际上非常简单:

public int avg(int[][] matrix , int n , int x , int y){
     int sum = 0;

     //the number of pixels to go left and right from the center of
     //the nxn-matrix
     int nHelper = n / 2;

     //ensure the left upper corner of your matrix is in bounds
     int x_start = (x - nHelper < 0 ? 0 : x - nHelper);
     int y_start = (y - nHelper < 0 ? 0 : y - nHelper);

     //create sum of all elements in the nxn-matrix and in bounds of
     //the big matrix (assumption: the matrix is an array of columns
     int i , j;
     for(i = x_start ; i < x + nHelper + 1 && i < matrix.length ; i++)
          for(j = y_start ; j < y + nHelper + 1 && j < matrix[i].length ; j++)
                sum += matrix[i][j];

     //calculate the average
     return sum / ((i - x_start)  * (j - y_start));
}

这计算nxn矩阵的平均值,其中x,y为中心。你不应该把它转移到使用图像上太困难了。虽然不同的方法可能更有效,但如果要计算矩阵中所有单元格的平均值。但它显示了基本的想法。