【发布时间】:2013-12-05 05:51:12
【问题描述】:
所以,我正在做一个任务,让课程接收为康威的生命游戏设置的文本文件。我已经编写了所有内容,但是由于我对错误处理很烂,因此很难对其进行测试。我已经阅读了有关 try、catch、throw 等的 java 教程页面。我不明白,如果我能得到一些解决 IndexOutOfBounds 错误的东西,它将为我节省很多时间。
public void computeNextGeneration(int generation) {
int aliveCount;
tempBoard = new char[Column][Row];
int generationCount = 1;
System.out.print("Generation" + generationCount);
print();
do {
for (int i = 0; i < Row; i++) {
for (int j = 0; j < Column; j++) {
aliveCount = 0;
try {
if (board[Row - 1][Column - 1] == 'X') {
aliveCount++;
}
if (board[Row - 1][Column] == 'X') {
aliveCount++;
}
if (board[Row - 1][Column + 1] == 'X') {
aliveCount++;
}
if (board[Row][Column - 1] == 'X') {
aliveCount++;
}
if (board[Row][Column + 1] == 'X') {
aliveCount++;
}
if (board[Row + 1][Column - 1] == 'X') {
aliveCount++;
}
if (board[Row + 1][Column + 1] == 'X') {
aliveCount++;
}
if (board[Row + 1][Column + 1] == 'X') {
aliveCount++;
}
if (board[i][j] == 'X') {
if (aliveCount < 2) {
setCell(j, i, 0);
}
if (aliveCount > 2) {
setCell(j, i, 0);
} else {
setCell(j, i, 1);
}
}
if (board[i][j] == '0') {
if (aliveCount == 3) {
setCell(j, i, 1);
}
}
} catch (IndexOutOfBoundsException e) {
}
throw new IndexOutOfBoundsException();
}
board = tempBoard;
generationCount++;
System.out.print("Generation" + generationCount);
print();
System.out.println();
generation--;
}
} while (generation > 1);
}
第一种情况,在二维数组的边缘会给出第一个错误。我想如果我把检查相邻数组索引的代码放在一起......老实说,我只是把代码放在一起,就像在黑暗中拍摄一样。如果我能得到一个与我的问题类似的示例,任何可以说明处理 IndexOutOfBounds 错误的示例,我将不胜感激。
【问题讨论】:
-
不要将 try catch 用于已知发生的行为,而是用于意外行为,例如服务器在传输过程中断开连接。对这类事情使用 if 语句。
-
你如何声明
board数组? -
我刚刚在我的 GameOfLife 类中发布了一个方法,其中场板被实例化。 @Masud
标签: java error-handling