我试图解决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; } } }}编译器不应该在这里抛出“无返回语句”错误吗?
3 回答
慕的地8271018
TA贡献1796条经验 获得超4个赞
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赋值的路径,因此编译器没有理由抱怨。
慕妹3242003
TA贡献1824条经验 获得超6个赞
这是因为您没有为循环计数器指定角值。如果你添加 smth likei<N;或者j<N;你会得到编译器警告。但在此之前,它与以下内容相同:
while (true) {
}
添加回答
举报
0/150
提交
取消