此方法必须返回 boolean 类型的结果,java

2022-01-19 00:00:00 typeerror boolean java
 public boolean Winner() {
    for (int z = 0; z < 3; z++) {
            if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]
                    ) {
                return true;
            } 
    }
    for(int i=0; i<7;i+=3){
        if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {

    return true;}
    }
}

它返回给我这个错误:这个方法必须返回一个布尔类型的结果.我做错了什么?

It returns me this error: this method must return a result of type boolean. What am I doing wrong?

推荐答案

目前,该函数不保证返回 boolean,因为可能没有 if 语句将永远被输入.

Right now, the function isn't guaranteed to return a boolean, because it's possible that neither of the if statements will ever be entered.

你可以像这样修复它(但只有如果它确实是你的逻辑需要的时候这样做!):

You could fix it like this (but only do this if it's actually what your logic needs!):

public boolean Winner() {
    for (int z = 0; z < 3; z++) {
            if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]
                    ) {
                return true;
            } 
    }
    for(int i=0; i<7;i+=3){
        if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {

    return true;}
    }

    return false;
}

相关文章