我有一个for
循环,用于比较用户登录详细信息以启动应用程序的下一个屏幕。
如果用户输入的字段与数据库返回的ArrayList
中的数据成功匹配,则程序将启动下一个屏幕 - 如果它们不匹配,则会使用{{1}向用户输出错误消息}。
我的问题是JOptionPane
循环的每次迭代都会输出错误消息,但我希望消息只显示一次。
for
答案 0 :(得分: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");
}
<强>更新强>
正如@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
}
答案 1 :(得分:0)
正如上面的评论所说:你也可以使用地图而不是两个列表
Map<String,String> map = new HashMap<String,String>();
map.put("john", "1234");
map.put("test", "asdf");
String name = "test";
String password = "asdf";
//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("")) {
if(map.get(name)!=null && map.get(name).equals(password))
myHomeGUI.setVisible(true);
break;
} else {
JOptionPane.showMessageDialog(null,"Sorry, no user recognized with those credentials\nPlease try again");
}
} else {
JOptionPane.showMessageDialog(null,"Sorry, no fields can be left blank");
}//end
答案 2 :(得分:0)
如果您将代码重构为更多逻辑部分,则编码和理解将更加容易,例如:
if (name.equals("") || password.equals("")) {
JOptionPane.showMessageDialog(null,"Sorry, no fields can be left blank");
} else if(doesUserExist(name, password)) {
myHomeGUI.setVisible(true);
} else {
JOptionPane.showMessageDialog(null,"Sorry, no user recognized with those credentials\nPlease try again");
}
// ... new method
private boolean doesUserExist(String name, String password) {
for (int i = 0; i < passwords.size(); i++) {
if (name.equals(userNames.get(i)) && (password.equals(passwords.get(i)))) {
return true;
}
}
return false;
}