[英]Why am I getting “missing return statement” error in Java even though I have return statement and exception in thread main error in 2nd class?
[英]Why do I get an error for not having a return statement even though I have one in my for loop?
我正在編寫一個方法,它是大學作業的 Queue 類的一部分。 它應該搜索一個對象的鏈接列表,如果找到,則返回該對象的索引,如果沒有,則返回 -1。 當我沒有“返回 -1;”時下面的代碼中的語句我收到一個錯誤,說當我在 for 循環中顯然有一個上面的語句時,我沒有返回語句。 這里有什么問題?
public int find(Object item) {
Node current = head;
for(int index = 0; index < size; index++) {
if(current.data.equals(item)) {
return index;
}
else {
current = current.next;
}
}
return -1;
}
不清楚 size 在哪里定義,但假設index < size
永遠不是真的,那么你的 return 語句永遠不會被看到
因此,方法作用域需要所有可能的代碼路徑的最終返回語句
因為在編譯時編譯器不知道變量的值。 因此編譯器無法評估條件並檢查條件是真還是假。 因此消除了給出錯誤的“return -1”語句。 希望這能消除您的困惑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.