【发布时间】:2019-03-08 19:08:44
【问题描述】:
我在 Java 中为数独游戏编写这段代码已有一段时间了,我不知道出了什么问题,也许是“if”或 de “For”,但 IDE 说我的方法没有返回一个布尔类型。
// check if the number has already been used in the columns
private boolean checkColumns(int x, int y, int value) {
for (int j = 0; j < 9; j++) {
if (this.gridPlayer[j][y].getValue() == value) return false;
else return true;
}
}
// Check if the number has already been used in the lines
private boolean checkLines(int x, int y, int value) {
for (int i = 0; i <= 9; i++) {
if (this.gridPlayer[x][i].getValue() == value) return false;
else return true;
}
}
// Check if the number has already been used and the subGrid
private boolean checkSubGrid(int x, int y) {
for (int i = 0; i <= 9; i++) {
for (int j = 0; j <= 9; j++) {
if (this.gridPlayer[x][y].getValueOfSubGrid(x, y) == this.gridPlayer[i][j].getValueOfSubGrid(i, j)) {
if (this.gridPlayer[x][y].getValue() == this.gridPlayer[i][j].getValue()) {
return false;
} else {
return true;
}
} else if (this.gridPlayer[x][y].getValueOfSubGrid(x, y) != this.gridPlayer[i][j].getValueOfSubGrid(i,
j)) {
return true;
}
}
}
}
【问题讨论】:
-
如果
else if检查返回假怎么办? -
编译器抱怨哪种方法?
-
除非你在玩 10 格数独,否则我建议你可能指的是
i < 9和j < 9。 -
哪种方法?您发布了 3。
-
你确定这些循环的逻辑是对的吗?在大多数情况下,无论如何都会返回一个值,从而使循环成为单次迭代,从而使循环变得不必要。在任何情况下,
checkSubGrid并不能处理所有情况,而且寻找回报的逻辑也不是很聪明,你会希望在for循环之外返回。
标签: java arrays for-loop if-statement return