繁体   English   中英

Java 2D数组错误

[英]Java 2D array error

因此,我需要对每个元素进行2D数组计算,然后将其转移到另一个2D数组中,同时使用当前元素的“左”,“右”,“上”和“下”值。 如果当前元素在边缘上(x = 0,y = 0,x = array.length,y = array.length),我将得到一个数组越界错误。 我想创建一个处理每种情况的for循环,但是我不知道该怎么做。 我的代码示例是

private void buildE(int[][] array, int y, int x)
{

    int up = array[y - 1][x];
    int down = array[y + 1][x];
    int left = array[y][x - 1];
    int right = array[y][x + 1];

    if(up == 0){

        buildETopRow(array);

    }

E将是我的新数组。 此方法不起作用,因为y不等于0,它根本不存在,但我也无法将ints设置为null。 如果出现超出范围的错误,我需要超出范围的元素(上,下,左或右)等于当前元素。 有没有办法我仍然可以为此使用for循环,还是需要做其他事情?

如果我没看错,您想有效地将​​边缘上的元素与边缘外的元素的差异视为0。如果是这样,我将编写四个方法right(),left(),up()和down() ,下面以down()为例:

 /*
  * Return the difference between an element an the element below it
  */

public void down(int x, int y) {

    if (y == array.length - 1) { 
       \\ on the bottom edge
       return 0;
    }   

    return array[y][x] - array[y + 1][x];

}

在循环中,您将计算:

up(x,y) + down(x,y) + right(x,y) + left(x,y)

或需要进行任何计算。

用边界区域包围阵列的最简单方法。 这样您的x尺寸实际上就是width+2

import java.util.*;
import java.lang.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int realWidth = 10;
        int realHeight = 10;
        int[][] in = new int[(realWidth+2)][(realHeight+2)];
        int[][] out = new int[(realWidth+2)][(realHeight+2)];
        for (int j = 1;j<realHeight+1;j++)
        {
            for (int i = 1;i<realWidth+1;i++)
            {
                int top = in[j-1][i];
                int bottom = in[j+1][i];
                int left= in[j][i-1];
                int right  = in[j][i+1];
                out[j][i] = operation(top,bottom,left,right);
            }
        }
    }
    public static int operation (int top,int bottom,int left,int right)
    {
        return top+bottom+left+right;
    }
}

我不太确定您的问题是什么,但是(1)遍历2D数组的通常结构是使用嵌套的for循环(一个在另一个内部),以及(2)当您需要环绕计数器时(例如2 ,3,0,1,2,...)使用余数运算符%

int numRows = theArray.length;
int numCols = theArray[0].length;

for (int i = 0; i < numRows; i++) {
    for (int j = 0; j < numCols; j++) {

        int right = theArray[(j+1) % numCols];
        int down = theArray[(i+1) % numRows];
        int left = theArray[(j+numCols-1) % numCols];
        int up = theArray[(i+numRows-1) % numCols];

        /* right, down, left, and up will be the elements to the right, down, 
           left, and up of the current element. Npw that you have them, you can 
           process them however you like and put them in the other array. */

    }
}

余数运算符A%B操作是,一旦A与B一样大,就会将A设置为零。由于B是数组的大小,因此恰恰是它太大时,会导致IndexOutOfBounds错误。 注意:这不是% 工作方式,但是是思考它工作的一种好方法。 要查找有关它的更多信息,可以在Google上对其进行搜索,我在这里找到了不错的解释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM