[] []和if语句在代码

时间:2015-05-18 19:38:28

标签: java arrays if-statement 2d

我在下面的代码中有一些关于if语句和可能的2D数组的问题,我在下面说明:

int[][]image =
    {
        {0,0,2,0,0,0,0,0,0,0,0,2},
        {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},
        {2,0,5,5,5,5,5,5,5,5,0,2},
        {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,2,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 [] []。每个smooth [] []的元素都被8个边界元素加上其自身的数值平均值替换。

不应更改smooth [] [](数组外边框上的元素)中的边元素。

我尝试使用if语句执行此操作,但只有一半成功。顶部和左侧边框上的数字不会更改(r == 0 || c == 0),但底部或右侧边框上的任何数字都将更改为平均值。

    //compute the smoothed value of non-edge locations in smooth[][]

    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 || r == (image[c].length) || c == (image[r].length))
        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

2 个答案:

答案 0 :(得分:3)

您正在阻止您过早处理if语句以捕获右侧和底部边框情况。您的for循环条件:

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

在到达右列或底行之前停止处理。由于所有零,0的默认值恰好与那里的平均值相匹配。

if语句通过更改for循环条件以包含右边框和底边框来捕获边框情况 - 不要从长度中减去1

for(int r=0; r<image.length; r++)     
{// x-coordinate of element

    for(int c=0; c<image[r].length; c++)      
    { //y-coordinate of element

但是你必须正确地测试你的“在右边”和“在底部”的条件。从这里的length s减去一个。

if(r == 0 || c == 0 || r == (image[c].length - 1) || c == (image[r].length - 1))
    smooth[r][c] = image[r][c]; 

答案 1 :(得分:1)

似乎问题就在这里

if(r == 0 || c == 0 || r == (image[c].length) || c == (image[r].length))
    smooth[r][c] = image[r][c];

如果单元格是边缘(r == 0 || c == 0 || ...),那么您就是在这里说的,但是您犯了一个小错误。请记住,最后一个元素是长度减一,例如(... r == (image[c].length - 1) || c == (image[r].length - 1))

Cool bonus visual:

         (array.length) is this ─┐ (notice it doesn't exist)
  (array.length - 1) is this ─┐  │
                              v  v
     array | [x] [x] [x] [x] [x]
element is | 1st 2nd 3rd 4th 5th
  index is |  0   1   2   3   4
  

编辑:下面的内容都是正确的,但我被你使用“平等”这个词所甩掉,但更多的是我的草率阅读。因为它是真实和正确的我会离开它,但它与这个问题无关。

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

这不会创建一个与之相等的新数组,而是创建一个大小相同的新数组。它将新数组中的所有元素初始化为0,而不是您认为它正在做的事情。使用for的{​​{1}}个循环来正确复制。