为什么 eclipse 说我的方法没有返回有效结果?



我已经在 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;
}
}
}
}

编译器假设它不能 100% 确定 return 语句来自内部 您的"for"循环将被调用,因此它会看到一条路径,其中您的方法不返回任何值,即使它们声明了它们返回任何值。

你需要在你的循环之外有一些返回值,即使你确定这永远不会发生,即

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;
}
return false; //even if you think it will never be run it is necessary 
}

欢迎,
在您的checkSubGrid()方法中,如果运行时在最后一else if中没有输入,则需要返回一个值:else if (this.gridPlayer[x][y]...) {

如果该方法不void,则需要返回。

if(a > 1) {
return a;
} else {
return b;
}

在上面的例子中,我们有一个if - else语句,该方法将始终返回 true 或 false(或有异常(。

if(a > 1) {
return a;
} else if(a == 0) {
return b;
}

另一方面,该方法可以或不能在第二if中输入,它们没有回报。您没有确保编译器将有返回。

你可以解决这个问题,放置一个默认返回,或者放置一个 else 语句。

if(a > 1) {
return a;
} else if(a == 0) {
return b;
} else {
return null;
}

if(a > 1) {
return a;
} else if(a == 0) {
return b;
}
return null;

最新更新