Java 在try中返回带有if的布尔值
我不知道为什么aI不能返回真假。它打印“缺少返回语句” 我在网上寻找答案,但没有一个能解决我的问题Java 在try中返回带有if的布尔值,java,database,jdbc,Java,Database,Jdbc,我不知道为什么aI不能返回真假。它打印“缺少返回语句” 我在网上寻找答案,但没有一个能解决我的问题 public boolean Verification(String SQL) throws IOException{ try{ Statement statementCount=connection.createStatement(); ResultSet results = statementCount.executeQuery(SQL);
public boolean Verification(String SQL) throws IOException{
try{
Statement statementCount=connection.createStatement();
ResultSet results = statementCount.executeQuery(SQL);
String Cont=results.getString("ContadorFecha");
int cont=Integer.parseInt(Cont);
if (cont>=10){
return true;
} else {
return false;
}
}catch(SQLException ex) {
ex.printStackTrace();
System.out.println("Exception in register: " + ex);
}
}
对于所有可能的场景,您都需要一个return语句 在这个例子中,似乎是因为:
if (cont>=10){
return true;
} else {
return false;
}
这实际上可以被以下内容所取代:
return cont >= 10;
但是:如果在此之前抛出了异常怎么办
try块已完成,并且已处理(如果是这种类型的异常)
添加
return false;
在你被拦截后,你所有的案子都会被覆盖。JVM将知道每个场景返回什么,并且它将工作。由于catch块的原因,它缺少一个return语句
您也需要返回其中的内容,或者抛出异常。只需将其更改为:
public boolean Verification(String SQL) throws IOException {
try {
Statement statementCount = connection.createStatement();
ResultSet results = statementCount.executeQuery(SQL);
String Cont = results.getString("ContadorFecha");
int cont = Integer.parseInt(Cont);
if (cont >= 10) {
return true;
}
} catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Exception in register: " + ex);
}
return false;
}
在
catch
块中不返回任何内容。所以有一个缺少的return语句,正如错误所说,“但它们都不能解决我的问题”对不起,这完全是不真实的。这个问题有上千种版本,有明确的答案,其中很多就在这里。最简单的搜索为我们提供了try/catch
、if/else
、justif
…只有一半的答案:如果引发了另一种(未捕获)类型的异常怎么办?>如果引发了另一种(未捕获)类型的异常怎么办如果引发了RuntimeException,则不需要返回(显然)@Stultuske:只需在catch
块中添加一个return
。如果发生非SQLException
的内容,该方法将抛出,但不会返回。@t.J.Crowder nyah。。。长的day@911DidBush别理我的话
public boolean Verification(String SQL) throws IOException {
try {
Statement statementCount = connection.createStatement();
ResultSet results = statementCount.executeQuery(SQL);
String Cont = results.getString("ContadorFecha");
int cont = Integer.parseInt(Cont);
if (cont >= 10) {
return true;
}
} catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Exception in register: " + ex);
}
return false;
}
public boolean Verification(String SQL) throws IOException{
Boolean flag=false;
try{
Statement statementCount=connection.createStatement();
ResultSet results = statementCount.executeQuery(SQL);
String Cont=results.getString("ContadorFecha");
int cont=Integer.parseInt(Cont);
if (cont>=10){
flag=true;
}
}catch(SQLException ex) {
ex.printStackTrace();
System.out.println("Exception in register: " + ex);
}
return flag;
}