为什么编译器不抛出“无返回语句”的错误?

我试图解决Leetcode 中的一个问题,讨论的解决方案之一如下:


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;

            }

        }

    }

}

编译器不应该在这里抛出“无返回语句”错误吗?


慕的地6264312
浏览 162回答 3
3回答

慕的地8271018

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循环。因此,for除了return语句之外,外循环没有退出条件。没有方法不能为其return赋值的路径,因此编译器没有理由抱怨。

米脂

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

慕妹3242003

这是因为您没有为循环计数器指定角值。如果你添加 smth likei<N;或者j<N;你会得到编译器警告。但在此之前,它与以下内容相同:while (true) {}&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java