二维阵列中的压缩代码

时间:2016-03-02 02:24:13

标签: java multidimensional-array integer sum

我想简化以下代码。我正在寻找一种方法来将a,b,c和d在一行中初始化为零,并且还有一种方法来压缩try / catch块。

另一个问题:如果我没有明确说明a,b,c和d为零,为什么它们默认不为0?我认为它是因为它们没有被初始化,如果这是我如何初始化整数而不使用4行呢?

我知道可能还有其他更短的方法来解决这个问题,我希望看到它们,但我也希望看到一个更短的trycatch方法来解决这个问题。

    //returns sum of tiles adjacent to (x,y) in the 2d array specified

    public static int sumAround(int[][] array, int x,int y){
    int a,b,c,d;
    a = 0;
    b = 0;
    c = 0;
    d = 0;
    try{
        a = array[x][y+1];
    }catch(ArrayIndexOutOfBoundsException e){
    }

    try{
        b = array[x][y-1];
    }catch(ArrayIndexOutOfBoundsException e){
    }

    try{
        c = array[x+1][y];
    }catch(ArrayIndexOutOfBoundsException e){
    }

    try{
        d = array[x-1][y];
    }catch(ArrayIndexOutOfBoundsException e){
    }

    return a + b + c + d;




    }

5 个答案:

答案 0 :(得分:1)

创建另一个从此方法调用的方法

private int getVal (int[][] array, int x,int y) {

     try{
        return array[x][y];
    }catch(ArrayIndexOutOfBoundsException e){
        System.out.println ("AIOOB");
    } 
    return 0;
}

然后你可以简单地称为

int a = getVal (array, x, y+1);
int b = getVal (array, x, y-1);
// etc

答案 1 :(得分:0)

不太确定try ... catch语句及其功能。但是为了压缩整数(a,b,c,d),您可以尝试在同一行中定义所有这些内容。其中:

int a = 0,b = 0,c = 0,d = 0;

这将起作用,因为定义可以用同一行上的逗号分隔。这也可以简单地定义没有声明的变量(变量并不总是需要声明)。

答案 2 :(得分:0)

a = b = c = d = 0;

另外,一般来说捕获ArrayIndexOutOfBoundsException是一个坏主意,因为它捕获其他RuntimeExceptions,例如NullPointerException。相反,在执行x + 1或y + 1之前检查数组的大小。对于x - 1或y - 1,我假设如果你去负,你只会处于危险之中,如果x,y大于初始数组,那么似乎是错误的数据会导致某种类型的InvalidArgumentException被抛出。

答案 3 :(得分:-1)

试试这个

public static int sumAround(int[][] array, int x, int y) {
        int a = 0, b = 0, c = 0, d = 0;
        try {
            a = array[x][y + 1];
            b = array[x][y - 1];
            c = array[x + 1][y];
            d = array[x - 1][y];
        } catch (ArrayIndexOutOfBoundsException e) {

        }
        return a + b + c + d;
    }

答案 4 :(得分:-1)

  1. 您定义的整数是局部变量。在java中,默认情况下不会初始化局部变量,但默认情况下,类中的变量将初始化为0(如果不将它们与其他值一起分配)。所以,你必须初始化这四个值。
  2. 为什么不尝试抛出异常。在你的情况下,捕获异常是没有意义的,因为它仍然会返回一个"正确的"结果实际上什么都没有!
  3. 试试这个:

    public static int sumAround(int[][] array, int x,int y) throws ArrayIndexOutOfBoundsException{
        return array[x][y+1] + array[x][y-1] + array[x+1][y] + array[x-1][y];
    }