猿问

if / else语句缺少返回语句

public int checkGuess(int g, int randomnumber){


    number=g;

    this.randomnumber= randomnumber;


    if (number == randomnumber)

        return 0;


    else if (number < randomnumber)

        return -1;


    else if (number > randomnumber)

        return 1;


}

为什么这给了我一个丢失的退货陈述错误?每个if / else都有返回值,最后一个括号出现错误


慕尼黑8549860
浏览 596回答 3
3回答

达令说

每个return语句都在一个if语句内。虽然从逻辑上讲这是不可能的,但是当所有if评估都不为真时,编译器需要返回。我建议:public int checkGuess(int number, int randomnumber){&nbsp; &nbsp; int retVal = 0;&nbsp; &nbsp; this.randomnumber= randomnumber;&nbsp; &nbsp; if (number == randomnumber) {&nbsp; &nbsp; &nbsp; &nbsp; retVal = 0;&nbsp; &nbsp; } else if (number < randomnumber) {&nbsp; &nbsp; &nbsp; &nbsp; retVal = -1;&nbsp; &nbsp; } else if (number > randomnumber) {&nbsp; &nbsp; &nbsp; &nbsp; retVal = 1;&nbsp; &nbsp; }&nbsp; &nbsp; return retVal;}我认为,此解决方案可解决编译器问题并稍微提高可读性。或者,有以下解决方案:public int checkGuess(int number, int randomnumber){&nbsp; &nbsp; this.randomnumber= randomnumber;&nbsp; &nbsp; if (number == randomnumber) {&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; } else if (number < randomnumber) {&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; } else if (number > randomnumber) {&nbsp; &nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; //throw an exception&nbsp; &nbsp; }}&nbsp; &nbsp;&nbsp;引发异常将使您可以退出该方法而无需返回任何信息……因为可以说,如果到达最后一个else,显然会出错。

狐的传说

您可以尝试将las更改else if为else。if (number == randomnumber)&nbsp; &nbsp; return 0;else if (number < randomnumber)&nbsp; &nbsp; return -1;else&nbsp; &nbsp; return 1;
随时随地看视频慕课网APP

相关分类

Java
我要回答