2016-04-21 72 views
-8

我有一個方法,搜索對象的數組列表並返回一個特定的對象的問題。錯誤是:缺少return語句。以下是代碼:如何搜索對象的數組列表並返回特定的對象?

public device lookUp(String theCode){ 
    for (int i = 0; i < availableDevices.size(); i++){ 
     if (availableDevices.get(i).getCode().equals(theCode)){ 
      return availableDevices.get(i); 
     } 
    } 
} 
+2

想什麼,如果對象沒有找到,會是什麼回來? –

+0

您的for循環之後,您需要返回一些內容,如果它在匹配輸入參數的for循環中找到,則只返回一些內容。通常人們會做類似返回null或拋出異常等。 – VeenarM

+0

@ D.Noze如果在方法的末尾放置返回語句,則不會再有錯誤。 – f1sh

回答

1

如果找到對象,則只返回。那麼如果沒有找到它會怎麼做。

只需在循環完成後立即添加return null;即可。它應該解決你的問題。

-1
public device lookUp(String theCode){ 
    String retVal = ""; 
    for (int i = 0; i < availableDevices.size(); i++){ 
     if (availableDevices.get(i).getCode().equals(theCode)){ 
      retVal = availableDevices.get(i); 
     } 
    } 
    return retVal; 
} 
+0

不起作用。 'String'!='device'。 – emlai

+0

OOPS我的壞。公共設備lookup(String theCode){device} retVal = new device();對於(int i = 0; i

1

在這種方法中:

public device lookUp(String theCode){ 
    for (int i = 0; i < availableDevices.size(); i++){ 
     if (availableDevices.get(i).getCode().equals(theCode)){ 
      return availableDevices.get(i); 
     } 
    } 
} 

必須添加返回NULL;如果你的availableDevices裏面有0行,那麼你的方法改變如下:

public device lookUp(String theCode){ 
    for (int i = 0; i < availableDevices.size(); i++){ 
     if (availableDevices.get(i).getCode().equals(theCode)){ 
      return availableDevices.get(i); 
     } 
    } 
    return null; // no elements in availableDevices 
} 
1

並非所有的執行路徑都有一個return語句。在這種情況下,您將遇到編譯錯誤。

嘗試類似這樣的東西。

public device lookUp(String theCode){ 
    for (int i = 0; i < availableDevices.size(); i++){ 
     if (availableDevices.get(i).getCode().equals(theCode)){ 
      return availableDevices.get(i); 
     } 
    } 
    return null //Device not found 
} 

基本上可能會有一些可能性,您的循環完成時不輸入if條件。在這種情況下,該函數沒有返回語句。

2

您可以在不返回語句的情況下到達函數的結尾。你的代碼應該看起來像:

public device lookUp(String theCode){ 
    device dev = null; 
    for (int i = 0; i < availableDevices.size(); i++){ 
     if (availableDevices.get(i).getCode().equals(theCode)){ 
      dev = availableDevices.get(i); 
      break; 
     } 
    } 
    return dev; 
} 
3

你return語句裏面if這意味着它可能會或可能不會返回值,但該方法應該返回一些value.To保證,編譯器會強迫你寫這個return語句出局條件。

3

試試這個:

public device lookUp(String theCode){ 
for (int i = 0; i < availableDevices.size(); i++){ 
    if (availableDevices.get(i).getCode().equals(theCode)){ 
     return availableDevices.get(i); 
    } 
} 
return null; 
} 
0

實現這樣

public device lookUp(String theCode){ 
    device dev = null; 
    for (int i = 0; i < availableDevices.size(); i++){ 
     if (availableDevices.get(i).getCode().equals(theCode)){ 
      dev = availableDevices.get(i); 
     } 
    } 
    return dev; 
} 
  • 在這裏,所以你需要先創建 它要返回 「設備」 的對象帶空引用,然後在「if」中分配新值並返回 那個對象。
0

按照方法定義,您應該返回設備對象。

public device lookUp(String theCode) 

您正在返回if語句中的設備對象。

如果條件失敗,那麼如果塊和方法不返回任何結果,控件將不會進入內部。 這就是爲什麼它顯示缺少返回錯誤。

循環後,您return null避免這種錯誤