java - 如何让 else block 在 for 循环中只执行一次

标签 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

最佳答案

发生这种情况是因为您将 else 条件 放入您的 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");
}

更新

正如@Joelblade 所建议的,您还可以将此身份验证逻辑转移到一个单独的方法中

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

然后检查你的LoginController

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

关于java - 如何让 else block 在 for 循环中只执行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28695842/

相关文章:

Excel嵌套IF语句

python-2.7 - 有没有比这更好的方法来实现强化学习的 Softmax Action 选择?

java - ResultSet(JDBC)如何按列名返回值

java - Runtime.exec().waitFor() 不会等到进程完成

java - Jmeter:groovy 脚本中 jmeter 对象的包装器

java - 我可以以某种方式排除或过滤掉 java 中 Collections.Min/Collections.Max 中的值吗?

java - 如何使用 postgis 和 Hibernate Spatial 5.2 正确映射具有 SRID 的多边形

Java Triple DES 算法 填充模式

Java 预计会执行 else,但始终会执行 if

javascript - 如何将错误消息放入 if 语句 if(...)