2011-08-02 157 views
2

我知道這看起來像是一個容易解決的問題,但我在這段代碼中找不到我的錯。我返回int,Eclipse告訴我'這個方法必須返回int類型的結果'。Java:返回值的問題

public static int getLastId(int table) { 

    Connection connection = null; 
    String url = "jdbc:postgresql://someServer:port/someDB"; 

    try { 
     //Verbindung herstellen 
     connection = DriverManager.getConnection(url, "someUser", 
       "somePassword"); 
     } catch (SQLException e1) { 
     //fehlerhafte Verbindung 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    try { 
     //0 - source ; 1 - destination Table 
     if(table == 0){ 

     Statement stmt = connection.createStatement(); 
     ResultSet lastId; 
     lastId = stmt.executeQuery("SELECT index FROM table0 ORDER BY someIndex DESC LIMIT 1"); 
     String theLastId0 = ""; 
     while(lastId.next()) 
      { 

       //System.out.print(lastId.getString("index")); 
       theLastId0 = lastId.getString("index"); 

      } 
      lastId.close(); 
      stmt.close(); 
      connection.close(); 
      int letzteId0 = Integer.parseInt(theLastId0); 

     return letzteId0; 

     }else if(table == 1){ 

      Statement stmt = connection.createStatement(); 
      ResultSet lastId; 
      lastId = stmt.executeQuery("SELECT index FROM table1 ORDER BY someIndexDESC LIMIT 1"); 
      String theLastId1 = ""; 
       while(lastId.next()) 
       { 

        //System.out.print(lastId.getString("index")); 
        theLastId1 = lastId.getString("index"); 

       } 
       lastId.close(); 
       stmt.close(); 
       connection.close(); 
       int letzteId1 = Integer.parseInt(theLastId1); 

      return letzteId1; 
      } 

    } 
    catch (SQLException e) { 

     System.out.println("Connection Failed! Check output console"); 
     e.printStackTrace(); 
     return -1; 
    } 
} 

回答

4

此方法必須始終返回一個int。

您必須在別人後面添加以下else語句

else { 
return 0; 
} 

,如果因爲你的版本,你不要,如果你的,如果返回任何東西,你的否則,如果計算結果爲假。

+0

非常感謝這是問題的最佳答案。即使我下班回家,我也不會想到的一件事是^^。有時你需要問一個問題,看看有時候會有多愚蠢。乾杯。 – 1amtoo1337

10

如果table != 0table != 1會發生什麼情況?那麼你的方法不會返回任何東西。因此,您可以將else聲明添加到if或者只是定期返回,並返回一個虛擬值,如-1。

即使你,程序員知道這種情況永遠不會被執行,編譯器也不知道,所以你必須讓它快樂起來。加上令人討厭的事情可以使用反射來完成,因此假設輸入到您的方法是有效的,這絕不是一個好主意。

+0

tskuzzy,你的言論也絕對正確,但是因爲曼努埃爾塞爾瓦給出了一個(在我看來)簡潔,更好和更短的解釋,他會得到答案。 – 1amtoo1337

1

如果table!= 0或1,那麼你的代碼不會返回任何東西。只需在最後添加return 0;或者任何適當的行爲,那麼你應該沒問題。

爲了將來的參考,如果指定了返回類型,您的方法必須在每個條件中返回一個值。如果有什麼情況沒有被返回,那麼代碼是錯誤的。希望能幫助到你!