【问题标题】:Java: This method must return a result type of type doubleJava:此方法必须返回 double 类型的结果类型
【发布时间】:2020-02-16 09:32:17
【问题描述】:

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

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;

【问题讨论】:

  • 这似乎不是一个完整的方法。可以分享一下完整的方法和结果吗?

标签: java methods return double


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    尝试以下方法:

    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
    

    【讨论】:

    • 我建议从最终的 return 语句中返回一个固定值,最好是 NaN。如果使用意外的值调用它,这将导致更容易调试。
    【解决方案3】:

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

    当 aantalBallen 不等于 0 、 1 或 =2 时,该 return 语句将用于从该方法返回 double。

    无论如何,即使所有条件都失败,该方法也需要返回一个值,在这种情况下为 Double。

    【讨论】:

      猜你喜欢
      • 2013-12-18
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多