【问题标题】:Why am I getting a "missing return statement" even though I have the statement in the code? [duplicate]为什么即使我在代码中有声明,我也会收到“缺少返回声明”? [复制]
【发布时间】:2016-03-04 10:37:27
【问题描述】:

当我确实包含了一个 return 语句时,我很难理解为什么这段代码会因为没有 return 语句而出现问题。任何帮助将不胜感激!

有问题的代码:

   public static int getSize()
   {
      Scanner kbd = new Scanner(System.in);
      int x = 1;
      while(x==1){
         System.out.println("Enter the size (>0): ");
         int n = kbd.nextInt();
         if (n>0){
            x--;
            return n;
         }
      }
   }

【问题讨论】:

    标签: java


    【解决方案1】:

    您收到错误是因为并非所有代码路径都返回值。

    在方法末尾添加这一行:return 0;

    public static int getSize()
    {
         Scanner kbd = new Scanner(System.in);
         int x = 1;
         while(x==1){
             System.out.println("Enter the size (>0): ");
             int n = kbd.nextInt();
             if (n>0){
                x--;
                return n;
             }
         }
    
          return 0; // Add this line
    }
    

    假设n <= 0。那么现有的return 语句将永远不会被调用,因此该方法永远不会return。因此,您需要通过添加return 0 向编译器保证该方法无论如何都会返回默认值。

    【讨论】:

    • 非常感谢!作为 CS 的一年级学生,很高兴有这么多人愿意提供帮助。
    • 不客气 :) 祝你好运!
    【解决方案2】:

    因为你没有在你的代码中涵盖所有可能的方式,我的意思是,如果n>0 是假的,该方法将永远不会返回任何东西

    试试这个

       public static int getSize()
       {
          Scanner kbd = new Scanner(System.in);
          int x = 1;
          while(x==1){
             System.out.println("Enter the size (>0): ");
             int n = kbd.nextInt();
             if (n>0){
                x--;
                return n;
             }
          }
    
          // Bad response 
          return -1;
       }
    

    【讨论】:

      【解决方案3】:

      您的代码在所有情况下都不会到达 return 语句。您需要在循环外添加默认返回语句。

      【讨论】:

        【解决方案4】:

        循环中有一个return,但编译器不确定循环不会在没有命中该语句的情况下退出。因为它认为可能会到达函数的末尾,所以它给出了错误。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-04-08
          • 2019-02-27
          • 2016-05-06
          • 2012-08-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多