This question already has answers here:
“Missing return statement” within if / for / while
                                
                                    (7个答案)
                                
                        
                                4年前关闭。
            
                    
该程序使用3种不同的方法播放胡扯。我在玩掷骰子时需要帮助,但是我需要使用这3种不同的方法,但是由于某种原因,每次我编译时都会遇到此错误:

CrapsAnalysis.java:48: error: missing return statement
    }
    ^
1 error
Process javac exited with code 1


码:

public class CrapsAnalysis
{
public static int rollDie( int n) {
    return (int)(Math.random()*n) + 1 ;
}
public static int rollDice( ) {
    return rollDie(6) + rollDie(6) ;
}
public static boolean playOneGame( ) {
    int newDice = rollDice();
    int roll = rollDice(); //first roll of the dice
    int playerPoint = 0; //player point if no win or loss on first roll
    if (roll == 7 || roll == 11)
        return true;
    else if (roll == 2 || roll == 3 || roll == 12)
        return false;
    else
        playerPoint = roll;
    do {
        if (rollDice() == 7)
            return false;
        else if (rollDice() == playerPoint)
            return true;
        else
            newDice = rollDice();
        } while (rollDice() != playerPoint || rollDice() != 7) ;
    }
}

最佳答案

Java必须查看所有执行路径。如果while循环结束而不返回任何内容,会发生什么?您可能在逻辑上避免了这种情况,但是Java编译器不会进行这种分析。

return循环结束后提供一个while语句,或者,如果代码确实不应该在其中添加某种ExceptionIllegalStateException?),则可以使用它。

10-01 22:24
查看更多