大家好,我在几个大学作业中需要检查二维数组(网格)中的相邻单元格。我的解决方案使用异常有点像一个hack,我正在寻找一种方法来清理它,而不必像我的一些同学一样使用大量的 if
语句。我目前的解决方案是:
for ( int row = 0; row < grid.length; row++ ) {
for ( int col = 0; col < grid.length; col++ ) {
// this section will usually be in a function
// checks neighbours of the current "cell"
try {
for ( int rowMod = -1; rowMod <= 1; rowMod++ ) {
for ( int colMod = -1; colMod <= 1; colMod++ ) {
if ( someVar == grid[row+rowMod][col+colMod] ) {
// do something
}
}
}
} catch ( ArrayIndexOutOfBoundsException e ) {
// do nothing, continue
}
// end checking neighbours
}
}
我不敢想象使用异常让我的代码能够工作的低效率,因此我正在寻找建议,以便在不影响可读性的情况下消除对异常的依赖,如果可能的话,并使这段代码更加高效。提前感谢。