Java:返回值的问题
我知道这似乎是一个容易解决的问题,但我在这段代码中找不到我的错误。我返回int,Eclipse告诉我“这个方法必须返回int类型的结果”Java:返回值的问题,java,Java,我知道这似乎是一个容易解决的问题,但我在这段代码中找不到我的错误。我返回int,Eclipse告诉我“这个方法必须返回int类型的结果” public static int getLastId(int table) { Connection connection = null; String url = "jdbc:postgresql://someServer:port/someDB"; try { //Verbindung herstellen
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;
}
}
此方法必须始终返回int 必须添加以下else语句
else {
return 0;
}
在else if之后,因为在您的版本中,如果if和else if的计算结果为false,则不会返回任何内容。如果
表!=0和表!=1
?那么你的方法不会返回任何东西。因此,要么在if
中添加一个else
语句,要么只是一个常规返回,返回一个类似-1的伪值
即使你,程序员,知道这个案例永远不会被执行,编译器也不知道,所以你必须让它快乐。另外,使用反射可以完成一些令人讨厌的事情,因此假设方法的输入是有效的从来都不是一个好主意。If table!=0或1,则代码不会返回任何内容。只需添加返回0代码>在最后,或者不管适当的行为是什么,那么您应该很好
为了便于将来参考,如果指定了返回类型,则您的方法在每个条件下都必须返回一个值。如果出现不返回任何内容的情况,则代码是错误的。希望有帮助 非常感谢这是这个问题的最好答案。有一件事即使我下班回家也不会想到。有时候你需要问一个问题,看看一个人有时候有多愚蠢。干杯。tskuzzy,你的陈述也绝对正确,但由于曼努埃尔·塞尔瓦(在我看来)给出了一个简洁、更好、更短的解释,他会得到答案。