簡體   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