How to fix "the code enters to else part additionally" while loop problem in this code?

Leo :

I am trying to print username and password but, the code enters else part twice.

I added print functions for conditions.

  1. In the case of username and password matched, I took "Matched!" and "Invalid username or password!" messages.

  2. In case of the only username matched, I took "Username!" and "Invalid username or password!" messages.

  3. In case of the only password matched, I took "Password" and "Invalid username or password!" messages.

  4. In case of nothing matched, I got "Invalid username or password!" message twice.

Below is the code

Statement myStmt = myConn.createStatement();
ResultSet resultSet = myStmt.executeQuery("SELECT * FROM `Employee`");
while(resultSet.next()) {
    if(resultSet.getString("username").matches(textField_1.getText()) && resultSet.getString("password").matches(textField_2.getText())) {
        System.out.println("Matched!");
    } else {
        System.out.println("Invalid username or password!");
    }
}

The result suppose to be "Matched!" for valid password and username. The result suppose to be "Invalid username or password!" for invalid username or password.

Youssef Roshdy :
Statement myStmt = myConn.createStatement();
ResultSet resultSet = myStmt.executeQuery("SELECT * FROM `Employee`");
boolean check = false;
while(resultSet.next()){ 
    if(resultSet.getString("username").matches(textField_1.getText()) && resultSet.getString("password").matches(textField_2.getText())){ 
        System.out.println("Matched!");
        check = true;
        break;
    }

}
if (check == false){

      System.out.println("Invalid username or password!");
}

Now the while loop will search for the right username and password if not will print Invalid.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=161168&siteId=1