【问题标题】:Why doesn't the compiler throw an error saying "No return statement"?为什么编译器不会抛出“无返回语句”的错误?
【发布时间】:2019-03-12 12:21:52
【问题描述】:

我试图在 Leetcode 中解决 question,讨论的解决方案之一如下:

public class Solve {
    public static void main(String[] args) {
        String haystack = "mississippi";
        String needle = "issip";
        System.out.println(strStr(haystack,needle)) ;
    }

    public static int strStr(String haystack, String needle) {
        for (int i = 0; ; i++) {
            for (int j = 0; ; j++) {
                if (j == needle.length()) return i;
                if (i + j == haystack.length()) return -1;
                if (needle.charAt(j) != haystack.charAt(i + j)) break;
            }
        }
    }
}

编译器不应该在这里抛出“No return statement”错误吗?

【问题讨论】:

  • 没有。没有导致外部循环被终止并因此无法返回值的代码路径。现在,如果break 终止了外循环,您将有一个观点。但唯一可以终止外循环的条件是return i-1

标签: java return


【解决方案1】:
for (int i = 0; ; i++) {
    for (int j = 0; ; j++) {
       if (j == needle.length()) return i;
       if (i + j == haystack.length()) return -1;
       if (needle.charAt(j) != haystack.charAt(i + j)) break;
    }
}

这里的两个for 循环都是无限循环。 break 语句只跳出内部 for 循环。因此,除了return 语句之外,外部for 循环没有退出条件。没有任何路径是该方法不能return 的值,因此编译器没有理由抱怨。

【讨论】:

    【解决方案2】:

    你的两个 for 循环都是无限的,第二个循环总有一天会中断或返回!但是第一个甚至没有中断,那么Java知道你永远不会富到最后一行。

     for (int i = 0; ; i++) {
          //Your second loop which is capable of returning or breaking (the second one is not technically infinite.
     }
    

    【讨论】:

      【解决方案3】:

      第一个for 循环对于编译器来说是无限的,我们知道它会返回,但是编译器没有理由抱怨。好问题。

      【讨论】:

        【解决方案4】:

        这是因为您没有为循环计数器指定角值。 如果你添加像i<N;j<N; 这样的东西,你会收到编译器警告。 但在此之前,它与以下内容相同:

        while (true) {
        
        } 
        

        【讨论】:

          猜你喜欢
          • 2011-04-17
          • 1970-01-01
          • 2016-03-30
          • 2023-02-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-30
          • 1970-01-01
          • 2016-07-31
          相关资源
          最近更新 更多