java - [ ][ ] 和 if 语句的问题

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

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

相关文章:

java - PropertyPlaceholderConfigurer 用于查找数据库值并使用属性文件作为后备

java - 我的 psvm 类不运行其他类和方法

arrays - 给定索引获取三角矩阵的行和列

python如果用户输入包含字符串

java - 打印数组 : memory address or its content?

java - 如何在 Android 上设置选定日期前一天的通知

javascript - 这个数组排序功能实际上是如何工作的?

java - java中如何实例化一个成员类的数组

json - jq 忽略 else 子句

iOS - 检查选择了哪个 UITabBar 选项的简单方法