简体   繁体   中英

Can you stop checking a if once it has passed once, in a while loop?

I don't need the if after its condition has been met. Is there any way I can modify my code so that it doesn't have to check for it after it passed? I have a lot of tables in my database and I'm wondering if the code is optimal.

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM STACKOVERFLOW.information_schema.tables ORDER BY TABLE_NAME");
while (rs.next()) {
    String name = rs.getString("TABLE_NAME");
    ExtractFrom.addItem(name);         
    if (name.toLowerCase().equals("stack")) pvIsPresent=true;
}
if (pvIsPresent)
    ExtractFrom.setSelectedItem("stack");

You could just do if (!pvIsPresent && name.toLowerCase().equals("stack")) .

Although you might also want to use the slightly more efficient name.equalsIgnoreCase("stack") .

This is somehow ugly but...

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM STACKOVERFLOW.information_schema.tables ORDER BY TABLE_NAME");

while (rs.next()) {
    String name = rs.getString("TABLE_NAME");
    ExtractFrom.addItem(name);

    if (name.toLowerCase().equals("stack")) {
        pvIsPresent = true;
        break;
    }
}

while (rs.next()) {
    String name = rs.getString("TABLE_NAME");
    ExtractFrom.addItem(name);
}

if (pvIsPresent)
    ExtractFrom.setSelectedItem("stack");

您可以将while语句更改为此:

while(rs.next && !pvIsPresent)...

More ugly and more simply maybe but you can put a counter before while as

  • "int counter = 0"

and in the if statement you can ask as

  • "if(..... && counter == 0)"

than after if statement you can increment the counter as

  • "counter++"

than since the counter never become 0 again the if statement never be checked again.

I hope it helps too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM