我正在为 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/