我的程序中有错误,我将在下面说明:

int[][]image =
    {
        {0,0,2,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,5,5,5,5,5,5,5,5,0,0},
        {0,0,0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0,0,0}//assume this rectangular image
    };

    int[][]smooth = new int[image.length][image[0].length]; //new array equal to image[][]

注意图像[] []。它是由一系列数字组成的2D数组。它下面的代码初始化了一个新的2D数组,该数组称为smooth [] [],与image [] []相同。

我用数组中包围它的八个元素(加上元素本身)的数值平均值替换smooth [] []中的每个元素。我已经做到了。

但是,请注意image [] []中位于数组边缘的元素。这些元素位于第0行和第0列。这些边缘元素中的任何一个,我都希望在smooth [] []中保持不变。我尝试使用if语句执行此操作,但是它不起作用。我该如何工作?
// compute the smoothed value of non-edge locations insmooth[][]
for (int r = 0; r < image.length - 1; r++) {// x-coordinate of element
    for (int c = 0; c < image[r].length - 1; c++) { // y-coordinate of
                                                    // element

        int sum1 = 0;// sum of each element's 8 bordering elements and
                     // itself

        if (r == 0 && c == 0) {
            smooth[r][c] = image[r][c];
        }

        if (r >= 1 && c >= 1) {
            sum1 =    image[r - 1][c - 1] + image[r - 1][c]
                    + image[r - 1][c + 1] + image[r]    [c - 1]
                    + image[r]    [c]     + image[r]    [c + 1]
                    + image[r + 1][c - 1] + image[r + 1][c]
                    + image[r + 1][c + 1];
            smooth[r][c] = sum1 / 9; // average of considered elements
                                     // becomes new elements
        }
    }
}

最佳答案

正如Phil所指出的,您的情况应该检查row == 0或col == 0

//compute the smoothed value of non-edge locations insmooth[][]
for(int r=0; r<image.length-1; r++){// x-coordinate of element
  for(int c=0; c<image[r].length-1; c++){ //y-coordinate of element

    int sum1 = 0; //sum of each element's 8 bordering elements and itself

    if(r == 0 || c == 0) {
      smooth[r][c] = image[r][c];
    }
    else {
      sum1 = image[r-1][c-1] + image[r-1][c] + image[r-1][c+1] + image[r][c-1] + image[r][c] + image[r][c+1] +image[r+1][c-1] + image[r+1][c] + image[r+1][c+1];
      smooth[r][c]= sum1 / 9; //average of considered elements becomes new elements
    }
  }
}

关于java - [] []和if语句的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30305545/

10-10 23:51