我有一个 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/