我不确定为什么,但由于某种原因,以下代码跳过了这个else条件.我已经尝试了我能想到的一切,包括切换代码块,但它仍然会跳过这else部分.基本上,String temp = "no"如果String docID在FILESTATUS数据库中找不到传递给方法的方法,并且String temp = "yes"找到它,我想要返回此方法.
static String checkDocID(String docID)
{
String temp = null;
System.out.println("Checking if data already exists in database...");
try
{
Main.stmt = Main.con.createStatement();
String command = "SELECT * FROM FILESTATUS WHERE ID='" + docID + "'";
ResultSet queryResult = Main.stmt.executeQuery(command);
if (!queryResult.next())
{
temp = "no";
}
else
{
while (queryResult.next())
{
String result = queryResult.getString("ID");
if (result.equals(docID))
{
temp = "yes";
break;
}
}
}
Main.stmt.close();
}
catch (Exception ex) {ex.printStackTrace();}
return temp;
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Pau*_*lin 16
因为您最终在"if"中再次调用queryResult.next()并且在while中再次调用,所以您将跳过第一个结果.如果只有一个结果,则while循环将永远不会执行.
如果我可以提出几点建议:
result.equals(docID)因为查询已经确定了.可能更好地重构此循环:
static String checkDocId(String docId) {
String temp = "no";
while (queryResult.next()) {
String result = queryResult.getString("ID");
if (result.equals(docID)) {
temp = "yes";
break;
}
}
return temp;
}
Run Code Online (Sandbox Code Playgroud)
有些人不喜欢使用break(我通常不喜欢)所以你可以在你的while中使用布尔值(我发现它更像是英语,你可以直接告诉终止条件while而不是寻找if内部):
static String checkDocId(String docId) {
boolean found = false;
while (queryResult.next() && !found) {
String result = queryResult.getString("ID");
found = result.equals(docID);
}
return found ? "yes" : "no";
}
Run Code Online (Sandbox Code Playgroud)
否则你正在进行一场不必要的比较.请记住,while仅仅是一个if带有goto末;)
就你的问题而言,保罗所说的是正确的.无论如何,我仍然会重新构造循环,以使它更优雅.
| 归档时间: |
|
| 查看次数: |
1017 次 |
| 最近记录: |