簡體   English   中英

為什么編譯器沒有拋出錯誤說“不返回語句”?

[英]Why doesn't the compiler throw an error saying “No return statement”?

我試圖在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;
            }
        }
    }
}

編譯器不應該在這里拋出“No return statement”錯誤嗎?

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值,因此編譯器沒有理由抱怨。

這是因為您沒有為循環計數器指定角點值。 如果你像i<N;那樣添加smth i<N; j<N; 你會得到編譯器警告。 但直到它與以下相同:

while (true) {

} 

對於編譯器來說,第一個for循環是無限的,我們知道它會返回,但編譯器沒有理由抱怨。 不錯的問題。

你的兩個for循環都是無限的,第二個就是有一天破壞或返回! 但是第一個甚至沒有休息,然后Java知道你從來沒有富裕到最后一行。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM