java - 从二维数组抛出异常后继续

标签 java exception try-catch

我正在为 Lights Out 构建模型我正在制作一个游戏,但在创建一个名为“flipSwitch”的方法时,我一直遇到问题。下面的代码打开或关闭指定的框,但如果我单击边框上的框,它会抛出 ArrayIndexOutOfBoundException,因为它无法关闭超出 2D 数组限制的框。

我尝试过使用 catch 中没有任何内容的 try-catch block ,但它不会尝试关闭其余的框,即使它们存在。我还尝试将 continue; 放入 catch 中,但它给出了错误:“无法在循环之外使用 continue。”

换句话说,我怎样才能继续我的代码并基本上忽略抛出的异常?下图显示了我想要完成的任务。

private int[][] grid = new int[5][5];

public void flipSwitch(int row, int col)
    {
        if(getState(row, col) == ON){
            grid[row][col] = OFF;
            grid[row+1][col] = OFF;
            grid[row-1][col] = OFF;
            grid[row][col+1] = OFF;
            grid[row][col-1] = OFF;
        }else{
            grid[row][col] = ON;
            grid[row+1][col] = ON;
            grid[row-1][col] = ON;
            grid[row][col+1] = ON;
            grid[row][col-1] = ON;
        }
        clickCount++;
    }

最佳答案

为了使此工作与“忽略ArrayIndexOutOfBoundException”一起工作,您需要为每个grid[..][..]一个try/catch = .. 行:

try { grid[row][col] = OFF; } catch (Exception e) {};
try { grid[row+1][col] = OFF; } catch (Exception e) {};
try { grid[row-1][col] = OFF; } catch (Exception e) {};
try { grid[row][col+1] = OFF; } catch (Exception e) {};
try { grid[row][col-1] = OFF; } catch (Exception e) {};

正如你所看到的,它看起来很糟糕。

编写以下方法会更好(也更干净):

private void switchState(int row, int col, int status) {
    if (/* check if 'row' is in bound */ && /* check if 'col' is in bound */) {
        grid[row][col] = status;
    }
}

然后这样调用它:

switchState(row, col, OFF);
switchState(row + 1, col, OFF);
switchState(row - 1, col, OFF);
switchState(row, col + 1, OFF);
switchState(row, col - 1, OFF);

这首先避免了异常并且更容易维护。如果您愿意,您也可以使用不同的名称:D。

关于java - 从二维数组抛出异常后继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33528215/

相关文章:

具有内存中字典的 Java servlet,它是线程安全的,并且可以重新初始化

java - 如何在 finally block 中输出变量?

java - 我可以在 Controller 的父抽象类中使用 ModelAttribute 吗

java - 如何更改Exception.getMessage()的返回消息?

java - 替换 pdf 文件——它可以与 sed 一起使用,但是当使用 Java 时,pdf 文件中的图像会消失。为什么?

android - IllegalArgumentException : Invalid int: "OS" with Samsung tts

java - 当我在 Android Studio 的菜单中说添加地点时,它有时会打开 map ,有时应用程序会在不打开的情况下关闭

java - 如何以OO方式修改返回值设计?

PHP:异常和可捕获的 fatal error 有什么区别?

php - 尝试/捕获不适用于 Laravel 5.4