如何让一个else块在for循环中只执行一次

RoR*_*o88 1 java if-statement

我有一个for循环,用于比较用户登录详细信息以启动应用程序的下一个屏幕.

如果用户输入的字段与ArrayList从数据库返回的数据成功匹配,则程序启动下一个屏幕 - 如果它们不匹配,则使用错误消息输出给用户JOptionPane.

我的问题是for循环的每次迭代输出错误消息,但我希望消息只显示一次.

  //if name or password are NOT left blank proceed with the check otherwise output error message in the text area
    if (!name.equals("") && !password.equals("")) {
        for (int i = 0; i < passwords.size(); i++) {
            if (name.equals(userNames.get(i)) && (password.equals(passwords.get(i)))) {
                myHomeGUI.setVisible(true);
                break;
            } else {
                JOptionPane.showMessageDialog(null,"Sorry, no user recognized with those credentials\nPlease try again");
            }
        }//end for loop 
    } else {
        JOptionPane.showMessageDialog(null,"Sorry, no fields can be left blank");
    }//end
Run Code Online (Sandbox Code Playgroud)

Nee*_*ain 5

这是发生,因为你把else condtion你的loop这每一个执行Iteration

试试这个 :

boolean isValid=false; 
for (int i = 0; i < passwords.size(); i++) {
            if (name.equals(userNames.get(i)) && (password.equals(passwords.get(i)))) {
                myHomeGUI.setVisible(true);
                isValid=true;
                break;
            }
 }//end for loop 
 if(!isValid) {
JOptionPane.showMessageDialog(null,"Sorry, no user recognized with those credentials\nPlease try again");
}
Run Code Online (Sandbox Code Playgroud)

更新

正如@Joelblade建议的那样,您也可以将此身份验证逻辑转换为单独的方法

public boolean  isAuthenticationPassed(String userName,String password){
              return true; // When Login Successfull
              or 
              return false; // When Login unsuccessfull 
    }
Run Code Online (Sandbox Code Playgroud)

然后检查你的LoginController

if(isAuthenticationPassed){
  // Do whatever you want to do 
}
else{
//Return to Login Page with error / or show Dialog Box
}
Run Code Online (Sandbox Code Playgroud)