[] []和if语句

时间:2015-05-18 14:12:59

标签: java arrays if-statement for-loop 2d

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

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数组。它下面的代码初始化一个名为smooth [] []的新2D数组,它与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
        }
    }
}

1 个答案:

答案 0 :(得分:2)

菲尔表示你的情况应该是检查行== 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
    }
  }
}