当循环找到匹配的用户名和密码时如何重置循环?

How to reset the loop when the loop found the matched username and password?

此代码部分是我程序中代码的一部分。我目前正在编写一个 GUI 程序。这部分代码即将从 ArrayList 中提取用户名和密码,如果匹配则允许用户登录。我想要的输出是如果这个循环找到匹配的用户名和密码,它将中断并继续到另一个界面;相反,如果没有匹配到,则循环继续寻找匹配的。那么,我的 if-else 应该如何呢?我无法弹出显示用户名和密码错误的消息,因为在 else 块中,我需要它循环直到找到匹配的。

public void actionPerformed(ActionEvent e){
        
        if(e.getSource() == loginButton){           
            for(int i =0;i<AcademicSystem.allUser.size();){
                User usr = AcademicSystem.allUser.get(i);
                User pswrd = AcademicSystem.allUser.get(i);
                
                System.out.println(usr.getLogin_username() + "\t" + userName.getText());
                System.out.println(pswrd.getLogin_password() + "\t"  + password.getText());
                System.out.println("");
                
                if(userName.getText().equals(usr.getLogin_username())&&password.getText().equals(pswrd.getLogin_password())){
                    JOptionPane.showMessageDialog(loginButton,"Username and password matched!");
                    JOptionPane.showMessageDialog(loginButton, "User[" + userName.getText() + "] have successfully logged in");
           
                    Dashboard db = new Dashboard();
                    setVisible(false);
                    db.setVisible(true);
                    break;
                }
                
                else if (!AcademicSystem.allUser.contains(userName.getText())&&!AcademicSystem.allUser.contains(password.getText())){
                   i++;
                }
            }
        }
    }

不要尝试在循环中做所有事情。在循环结束之前,您实际上并不知道应该采取什么操作,因此,循环遍历可用用户并找到符合条件的用户,或者,如果找不到,则让匹配保持 null .

然后当循环结束时,您可以检查 matched 对象的状态并采取适当的措施。

例如:

User matchedUser = null;

String userName = this.userName.getText();
String password = this.password.getText();
for (User user : AcademicSystem.allUser) {
    if (userName.equals(usr.getLogin_username()) && password.equals(pswrd.getLogin_password())) {
        matchedUser = user;
        break;
    }
}

if (matchedUser != null) {
    // You're good to go
} else {
    // Authentication failed
}

这种方法会让您将逻辑移动到 AcademicSystem,然后允许您将调用减少到更像:

User matchedUser = AcademicSystem.authenticate(userName.getText(), password.getText());
if (matchedUser != null) {
    // You're good to go
} else {
    // Authentication failed
}

这将验证用户的责任转移到它所属的域,并降低了流程中的整体代码复杂性,win/win