二维数组抛出异常后继续
Continue after exception is thrown from a 2D array
我正在为我正在制作的 Lights Out 游戏构建模型,但我一直 运行 在创建一个名为 flipSwitch
的方法时遇到问题。下面的代码打开或关闭指定的框,但如果我单击边框上的框,它会抛出 ArrayIndexOutOfBoundException,因为它无法关闭超出 2D 数组限制的框。
我试过使用一个 try-catch
块,但它不会尝试关闭其余的框,即使它们存在。我也试过把 continue;
放在 catch 中,但它给了我一个错误,说 "continue cannot be used outside of a loop."
换句话说,我怎样才能继续我的代码并基本上忽略抛出的异常?下图显示了我要完成的工作。
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++;
}
为了使用 "ignoring an 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.
我正在为我正在制作的 Lights Out 游戏构建模型,但我一直 运行 在创建一个名为 flipSwitch
的方法时遇到问题。下面的代码打开或关闭指定的框,但如果我单击边框上的框,它会抛出 ArrayIndexOutOfBoundException,因为它无法关闭超出 2D 数组限制的框。
我试过使用一个 try-catch
块,但它不会尝试关闭其余的框,即使它们存在。我也试过把 continue;
放在 catch 中,但它给了我一个错误,说 "continue cannot be used outside of a loop."
换句话说,我怎样才能继续我的代码并基本上忽略抛出的异常?下图显示了我要完成的工作。
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++;
}
为了使用 "ignoring an 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.