【问题标题】:Problems with [ ][ ] and if-statement[ ][ ] 和 if 语句的问题
【发布时间】:2015-07-30 02:18:07
【问题描述】:

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

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[][]

注意图像[][]。它是由一系列数字组成的二维数组。它下面的代码初始化了一个名为 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
        }
    }
}

【问题讨论】:

  • 看起来你应该使用 ||而不是 && 在您的两个 if 语句中。如果行为零或列为零,则它位于边缘。
  • 是的,这应该是正确的说法:if(r == 0 || c == 0)
  • 下次请正确格式化您的代码。
  • @Phil Anderson 和 Max:真是个错误。我知道这很简单。谢谢。
  • @Turing85 我怎么格式不正确?

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


【解决方案1】:

正如 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
    }
  }
}

【讨论】:

    猜你喜欢
    • 2015-12-18
    • 1970-01-01
    • 2012-11-19
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多