当我尝试使用 arraylist 验证用户名和密码时,我不断收到空指针异常,我不确定是什么原因造成的。用户将他们的信息输入到用户名和密码 JTextFields 中,并根据用户名和密码的硬编码列表进行检查。也许有人可以提出问题的根源或更合理的方法来做到这一点?
LoginUI,当 submitButton 被按下时
public class SubmitListener implements ActionListener{
public void actionPerformed(ActionEvent evt){
System.out.println("Submit button pressed");
String usernameToPass = usernameField.getText();
String passwordToPass = passwordField.getText();
System.out.println("username and password: "+usernameToPass+" "+passwordToPass);
if(theLoginCntl.authenticate(usernameToPass, passwordToPass)){
LoginUI.this.setVisible(false);
theLoginCntl.getMainMenuCntl();
}else{
System.out.println("Invalid Password!");
}
}
}
LoginCntl,身份验证方法
public class LoginCntl {
private UserList theUserList;
private LoginUI theLoginUI;
private ArrayList<String> validUsers;
private ArrayList<String> validPasswords;
public LoginCntl(){
theLoginUI = new LoginUI(this);
}
public void getMainMenuCntl(){
MainMenuCntl theMainMenuCntl = new MainMenuCntl();
}
public boolean authenticate(String username, String password){
validUsers = new ArrayList();
validUsers = theUserList.getValidUsers(); //code breaks on this line
System.out.println("validUsers has been initialized");
validPasswords = new ArrayList();
validPasswords = theUserList.getValidPasswords();
for (int i = 0; i < validUsers.size(); i++) {
if (validUsers.get(i).equals(username) && validPasswords.get(i).equals(password)) {
return true;
}
}
theLoginUI.passwordField.setText("");
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
return false;
//return true;
}
}
UserList 类,硬编码有效的用户名和密码组合
public class UserList {
private ArrayList<String> validUsers;
private ArrayList<String> validPasswords;
public UserList(){
validUsers = new ArrayList();
validPasswords = new ArrayList();
validUsers.add("user1");
validUsers.add("user2");
validUsers.add("user3");
validUsers.add("user4");
validUsers.add("user5");
validPasswords.add("password1");
validPasswords.add("password2");
validPasswords.add("password3");
validPasswords.add("password4");
validPasswords.add("password5");
}
public ArrayList<String> getValidUsers(){
return validUsers;
}
public ArrayList<String> getValidPasswords(){
return validPasswords;
}
}