loli
loli

Reputation: 1068

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

Upvotes: 0

Views: 77

Answers (4)

Recomer
Recomer

Reputation: 191

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.

Upvotes: 0

Swagin9
Swagin9

Reputation: 1002

You could change the while statement to this:

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

Upvotes: 0

Luca Fagioli
Luca Fagioli

Reputation: 13349

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

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198033

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

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

Upvotes: 5

Related Questions