Java会跳过其他条件

rya*_*mer 1 java jdbc

我不确定为什么,但由于某种原因,以下代码跳过了这个else条件.我已经尝试了我能想到的一切,包括切换代码块,但它仍然会跳过这else部分.基本上,String temp = "no"如果String docIDFILESTATUS数据库中找不到传递给方法的方法,并且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循环将永远不会执行.

如果我可以提出几点建议:

  • 在PreparedStatement中使用绑定变量,而不是在查询字符串中放入"docID"
  • 不要测试,result.equals(docID)因为查询已经确定了.
  • 首选boolean to String"yes"或"no"
  • 将结果设置为"no"或false,然后在循环中将其设置为"yes"或true.额外的分配可能比额外的测试更快,而且你可以跳过do {},而大多数人都觉得难以阅读.


Viv*_*ath 6

可能更好地重构此循环:

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末;)

就你的问题而言,保罗所说的是正确的.无论如何,我仍然会重新构造循环,以使它更优雅.