Java: 此方法必须 return double 类型的结果类型

Java: This method must return a result type of type double

我已经在这个代码上停留了大约一个小时,我就是找不到解决方案。 如果有人可以帮助我,我将非常感激。 提前致谢。

public double  berekenPrijs(int aantalBallen) {
    if (aantalBallen == 0) {
        return  0.80;
    }
    else if(aantalBallen == 1 ){
        return 0.80;
    }
    else if (aantalBallen <= 3 && aantalBallen >=2) {
        return 0.9 * aantalBallen * 0.80;

如果 aantalBallen 不在 0、1、2 和 3 之间,你的函数是什么return?

尝试以下操作:

public class Goovy123 {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(berekenPrijs(0));
        System.out.println(berekenPrijs(1));
        System.out.println(berekenPrijs(2));
        System.out.println(berekenPrijs(3));
    }

    static public double berekenPrijs(int aantalBallen) {
        if (aantalBallen == 0) {
            return 0;
        } else if (aantalBallen == 1) {
            return 0.80;
        } else if (aantalBallen <= 3 && aantalBallen >= 2) {
            return 0.9 * aantalBallen * 0.80;
        }
        return Double.NaN;
    }
}

样本运行:

0.0
0.8
1.4400000000000002
2.16

您还需要在最后一个 elseIf 块之后添加一个 return 语句。

当 aantalBallen 不等于 0、1 或 <= 3 和 >=2 时,return 语句将用于从该方法中 return 加倍。

不管怎样,即使所有条件都失败,该方法也需要 return 一个值,在本例中是一个 Double。