为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕的地6264312 2021-11-03 16:08:56
我试图解决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赋值的路径,因此编译器没有理由抱怨。


查看完整回答
反对 回复 2021-11-03
?
米脂

TA贡献1836条经验 获得超3个赞

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


查看完整回答
反对 回复 2021-11-03
?
慕妹3242003

TA贡献1824条经验 获得超6个赞

这是因为您没有为循环计数器指定角值。如果你添加 smth likei<N;或者j<N;你会得到编译器警告。但在此之前,它与以下内容相同:


while (true) {



查看完整回答
反对 回复 2021-11-03
  • 3 回答
  • 0 关注
  • 161 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信