【问题标题】:Error "Missing return statement" [duplicate]错误“缺少返回语句”[重复]
【发布时间】:2016-01-04 09:52:38
【问题描述】:

我正在运行这个 java 代码,我得到一个错误“缺少返回语句” 请帮忙。我在 windows 中使用 cmd 运行。

public class Fibonocci {

    public static void main(String[] args) {

        int i, limit, c;
        i = 0;
        limit = 5;
        System.out.println("Fibonocci series :");
        for (c = 1; c <= limit; c++) {
            System.out.println(fib(i));
            System.out.println("/n");
            i++;
        }

    }

    public static int fib(int p) {
        if (p == 0) {
            return 0;
        }
        if (p == 1) {
            return 1;
        } else if (p > 1) {
            return (fib(p - 1) + fib(p - 2));
        }
    }
}

【问题讨论】:

  • 这可能是一个类,但迭代地实现斐波那契会更有效:)

标签: java


【解决方案1】:

您缺少默认的return。您从ifelse if 返回。

如果两个条件都不满足怎么办?您也需要提供。

我想建议返回-1 id 这两个条件都不满足,这是负数negative

public static int fib(int p) {
        if (p == 0)
            return 0;
        else if (p == 1)
            return 1;
        else if (p > 1)
            return (fib(p - 1) + fib(p - 2));
        else
            return -1;
    } 

【讨论】:

  • 谢谢,现在可以正常使用了。
【解决方案2】:

如果p&lt;0,您的代码不会返回任何内容。

你可以改成:

  public static int fib(int p){
      if (p<=0) // or perhaps you wish to throw an exception if a negative value is entered
          return 0;
      else if (p==1)
          return 1;
      else // when you end the if statement in else instead of else-if
           // your method is guaranteed to return something for all inputs
          return(fib(p-1)+fib(p-2));
  }

【讨论】:

  • 谢谢,它现在工作正常。
猜你喜欢
  • 2013-03-21
  • 2021-05-27
  • 2014-01-09
  • 2013-10-27
  • 1970-01-01
  • 2020-05-28
  • 2014-06-06
  • 2013-04-27
  • 1970-01-01
相关资源
最近更新 更多