【发布时间】:2011-05-06 10:58:34
【问题描述】:
大家好,对于我的一些大学作业,我发现需要检查二维数组(网格)中的相邻单元格。我使用的解决方案有点像使用异常的黑客攻击,我正在寻找一种方法来清理它,而不会像我的一些同学那样使用大量 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
}
}
想到使用异常来使我的代码正常工作的原因,我不寒而栗,因此我正在寻找有关如何在不牺牲可读性的情况下从代码中消除对异常的依赖的建议,以及如何我可以使这个代码段通常更有效。提前致谢。
【问题讨论】:
-
不要过多指责,但例外应该是一些例外。事先验证输入几乎总是更好,尤其是在琐碎的情况下。否则,您可能会掩盖重要的异常并隐藏算法的缺陷。
-
我想摆脱异常的更多理由。同样,这只是完成任务的快速技巧,但我不满意就这样离开。
标签: java exception performance multidimensional-array