0

当我尝试使用 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;
}

}

4

2 回答 2

0

我建议您使用 TreeMap 而不是两个 ArrayList:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TreeMap;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;



public class Main extends JFrame {


    /* ============================ VARIBLES ============================ */

    /** Needed because JFrame implements the Serializable Interface. Forget it*/
    private static final long serialVersionUID = 959648274013445628L;

    /** The button to confirm */
    JButton okButton;

    /** The texfield for the username */
    JTextField usernameField;

    /** The texfield for the password */
    JTextField passwordField;


    /** Store our passwords.  A TreeMap will associate each login with its
     * respective password: no need to use 2 ArrayLists. Also, is much more
     * efficient. */
    private static TreeMap<String, String> passwords = new TreeMap<>();




    /* ======================= PASSWORDS HANDLING ======================= */

    /**
     * This will fill passwords with 'login1'+'password1' ... 'login4'+'password4'
     */
    private void fillPasswords(){

        for(int i=0; i<5; i++)
            passwords.put("login"+i, "password"+i);
    }


    /**
     * Return if a username-password pair is a valid login .
     * 
     * @param username   The username
     * @param password   The password
     * @return   true if is a valid login, false otherwise.
     */
    public boolean authenticate(String username, String password){

        String storedPW = passwords.get(username);

        if(  storedPW == null ||          //<- The TreeMap hasn't any register for 'username'
            !storedPW.equals(password)  ) //<- There are a register for 'username', but it
            return false;                 //    does not match wit the password typed.

        return true;

        //Remember that you can't use the expression:   storedPW = password
        //That expression will be always false, because is comparing String references,
        //not String values.  For that reason, you need to use equals() method.
    }



    /* ========================= OTHER  METHODS ========================= */


    /** 
     * This is a fast, basic UI, modify it as you need.
     */
    private void createUI(){

        setSize(460,175);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        setLayout(null);

        usernameField = new JTextField();
        add(usernameField);
        usernameField.setSize(120,30);
        usernameField.setLocation(50,50);

        passwordField = new JTextField();
        add(passwordField);
        passwordField.setSize(120,30);
        passwordField.setLocation(180,50);

        okButton = new JButton("Ok");
        add(okButton);
        okButton.setSize(100,30);
        okButton.setLocation(310,50);
        okButton.addActionListener( new SubmitListener(this) );
    }



    /**
     * Fill the passwords TreeMap and launch the UI
     */
    private Main(){

        fillPasswords();
        createUI();
    }



    public static void main(String[] args){

        new Main();
    }


}





/**
 * This class handles The event of pressing the okButton.
 */
class SubmitListener implements ActionListener{

    Main main;


    SubmitListener(Main main){
        this.main = main;
    }


    @Override
    public void actionPerformed(ActionEvent arg0) {

        String usernameToPass = main.usernameField.getText();
        String passwordToPass = main.passwordField.getText();

        if( main.authenticate(usernameToPass, passwordToPass) )
            JOptionPane.showMessageDialog(main, "Login sucessfull",
                    "Sucess", JOptionPane.DEFAULT_OPTION);

        else
            JOptionPane.showMessageDialog(main, "Password unknow, try again",
                    "Failure", JOptionPane.WARNING_MESSAGE);

        //Add this if you want the 2 textfield to be cleared after a login try:
        main.usernameField.setText("");
        main.passwordField.setText("");
    }

}
于 2013-11-10T05:28:54.547 回答
0

您需要在调用方法之前初始化 theUserList。像这样的东西:

validUsers = new ArrayList();    
theUserList= new UserList(); // like this
validUsers = theUserList.getValidUsers();     
System.out.println("validUsers has been initialized");
于 2013-11-10T04:24:07.850 回答