作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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/
我是一名优秀的程序员,十分优秀!