- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以,我正在做一项作业,让一个类(class)接收为 Conway 的 Game Of Life 设置的文本文件。我已经写了所有东西,但是很难测试,因为我的错误处理很糟糕。我已经阅读了关于 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 错误的例子,我将不胜感激。
最佳答案
乘坐 8 if
语句脱离 try-catch 场景,而是专注于检查索引是否为 board
是正确的。换句话说,在访问 board[Row - 1][Column - 1]
之前, 检查 0 <= Row-1 <= NumOfRows
和 0 <= Column-1 <= NumOfColumns
.
更明确的观点。
for (int i = 0; i < NumOfRows; i++) {
for (int j = 0; j < NumOfColumns; j++) {
aliveCount = 0;
if (i-1 >= 0 && i-1 <= NumOfRows) {//This case checks the cell to the left
aliveCount++;
}
//Other cases
关于java - GameOfLife IndexOutOfBounds 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20392462/
我想尝试编写 Wator/GameOfLife。我有这两种方法来填充 gameField 并绘制它。 public void FillGameField() {
所以,我正在做一项作业,让一个类(class)接收为 Conway 的 Game Of Life 设置的文本文件。我已经写了所有东西,但是很难测试,因为我的错误处理很糟糕。我已经阅读了关于 try、c
我是一名初学者,试图通过遵循 John Ferguson 的“Jenkins 权威指南”来学习 Jenkins。我已经从 github 下载了示例项目“gameoflife”,并为 Maven、Git
我是一名优秀的程序员,十分优秀!