我是java的新手,我正在开发一个典型的记事本程序,可以让你保存,编辑,删除和创建笔记。对于应用程序,我正在尝试将身份验证添加到我的登录页面。我在UserList的初始化时遇到问题。我究竟做错了什么?很确定这是一个语法问题,我现在太过忘记了
UserList.java
import java.util.ArrayList;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UserList {
//Declares 2 arraylists, one for the list of usernames and one for passwords
private ArrayList<String> validUsernames;
private ArrayList<String> validPasswords;
private UserList theUserList;
//Constructor that adds usernames and passwords to the arraylists
public UserList() {
validUsernames = new ArrayList();
validPasswords = new ArrayList();
validUsernames.add("");
validUsernames.add("");
validUsernames.add("");
validUsernames.add("");
validUsernames.add("");
validPasswords.add("");
validPasswords.add("");
validPasswords.add("");
validPasswords.add("");
validPasswords.add("");
}
//Returns arraylist of valid users
public ArrayList<String> getValidUsernames() {
return validUsernames;
}
//Returns arraylist of valid passwords
public ArrayList<String> getValidPasswords() {
return validPasswords;
}
}
LoginCntl (验证方法)
public boolean authenticate(String username, String password){
validUsernames = new ArrayList();
**validUsernames = theUserList.getValidUsernames();** [line 42]
validPasswords = new ArrayList();
validPasswords = theUserList.getValidPasswords();
for (int i = 0; i < validUsernames.size(); i++) {
if (validUsernames.get(i).equals(username) && validPasswords.get(i).equals(password)) {
return true;
}
}
theLoginUI.password.setText("");
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
return false;
}
答案 0 :(得分:1)
此行有NullPointerException
:
validUsernames = theUserList.getValidUsernames();
唯一能导致此行NullPointerException
的是theUserList
为空。
确保在尝试访问之前初始化theUserList
。在这种情况下,在您调用身份验证之前。例如。您可以在声明时初始化它,如下所示:
UserList theUserList = new UserList();
或者你必须在尝试访问它之前检查null,并在那种情况下做一些适当的事情。例如
if(theUserList == null) {
// do something about it
}
validUsernames = new ArrayList();
validUsernames = theUserList.getValidUsernames();
...