使用ArrayList登录系统

时间:2013-03-04 05:58:41

标签: java arraylist

我正在尝试使用我创建的用户类创建一个登录系统,并在ArrayList中存储多个用户。然后,为了确保用户输入的各个字段与特定“用户”的内容相同,底部有一个比较两者的循环。底部的方法返回true或false。如果我不是以最明确的方式解释,我现在已经很晚了,我道歉。

我的问题是我的loginAuthorization()方法只返回true,当且仅当输入ArrayList中的第一个元素并且输入正确时。它忽略添加到ArrayList的所有其他用户。这个问题显然有一个“好的”答案,或者我认为,我不明白为什么会这样。如果有人能告诉我我做错了什么,我将不胜感激。 :)

我的loginWindow类:

    /**
     *  @author OperatorX© 2013
     */

    package dossierIB;

    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.Toolkit;

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
    import net.miginfocom.swing.MigLayout;
    import javax.swing.JLabel;
    import java.awt.Component;
    import javax.swing.Box;
    import java.awt.Dimension;

    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.JPasswordField;
    import javax.swing.JButton;
    import javax.swing.UIManager;

    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.util.ArrayList;
    import java.util.Arrays;

    public class LoginWindow extends JFrame 
    {
        private JPanel contentPane;
        private JFrame errorFrame;
        private JTextField usernameField;
        private JPasswordField passwordField;


        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                        LoginWindow frame = new LoginWindow();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the frame.
         */
        public LoginWindow() {
            setResizable(false);
            setTitle("Employee Authorization");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(100, 100, 450, 300);
            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            setContentPane(contentPane);
            contentPane.setLayout(new MigLayout("", "[][][][grow][]", "[][][][][][][]"));

            JPanel bgImagePanel = new JPanel();
            ImagePanel backgroundPanel = new ImagePanel(new ImageIcon("C:/Users/OpX/Documents/workspace/Dossier (WBP)/images/testtoptrans.png").getImage());
            bgImagePanel.add(backgroundPanel);
            contentPane.add(bgImagePanel, "cell 0 0 5 1");

            Component rigidArea_4 = Box.createRigidArea(new Dimension(20, 20));
            contentPane.add(rigidArea_4, "cell 4 1 1 6");

            JLabel lblUsername = new JLabel("Username");
            contentPane.add(lblUsername, "cell 1 2");

            Component rigidArea_1 = Box.createRigidArea(new Dimension(20, 20));
            contentPane.add(rigidArea_1, "cell 0 1 1 6");

            Component rigidArea_3 = Box.createRigidArea(new Dimension(20, 20));
            contentPane.add(rigidArea_3, "cell 2 2 1 3");

            usernameField = new JTextField();
            contentPane.add(usernameField, "cell 3 2,growx");
            usernameField.setColumns(10);

            Component rigidArea_2 = Box.createRigidArea(new Dimension(20, 20));
            contentPane.add(rigidArea_2, "cell 1 3");

            JLabel lblPassword = new JLabel("Password");
            contentPane.add(lblPassword, "cell 1 4");

            passwordField = new JPasswordField();
            contentPane.add(passwordField, "cell 3 4,growx");

            Component rigidArea_5 = Box.createRigidArea(new Dimension(20, 20));
            contentPane.add(rigidArea_5, "cell 1 5 3 1");


            JButton btnLogin = new JButton("Login");
            btnLogin.addActionListener(new ActionListener() 
            {
                public void actionPerformed(ActionEvent e) 
                {
                    if(loginAuthorization() == true)
                    {
                        ManageWindow manifest = new ManageWindow();
                        manifest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        manifest.setSize(697,500);
                        manifest.setLocationRelativeTo(null);
                        manifest.setVisible(true);

                        setVisible(false);
                        dispose();
                    }
                    else
                        return;
                }
            });
            contentPane.add(btnLogin, "flowx,cell 3 6,alignx right");

            JButton btnCreateAccount = new JButton("Create Account");
            btnCreateAccount.setEnabled(false);
            btnCreateAccount.addActionListener(new ActionListener() 
            {
                public void actionPerformed(ActionEvent e) 
                {

                }
            });
            contentPane.add(btnCreateAccount, "cell 3 6");
        }

        public Boolean loginAuthorization()
        {
            errorFrame = new JFrame();
            String username = usernameField.getText();
            String password = new String(passwordField.getPassword());

            ArrayList<User> users = new ArrayList<User>();
            User manager = new User("manager", "gocompany");
            User shiftManager = new User("shiftmanager", "goshifts");
            User stockBoy = new User("stockboy", "istockshelves");
            User cashier = new User("cashier", "trustedwithmoney");
            users.add(manager);
            users.add(shiftManager);
            users.add(stockBoy);
            users.add(cashier);

            for(int i = 0; i < users.size(); i++)
            {
                if(users.get(i).getUsername().compareTo(username) == 0 && users.get(i).getPassword().compareTo(password) == 0)
                {
                    return true;
                }

                else
                {
                    passwordField.setText("");
                    Toolkit.getDefaultToolkit().beep();
                    JOptionPane.showMessageDialog(errorFrame,
                            "Could not authorize employee with given username and password.\n\n" +
                            "Please reenter or contact your system administrator.\n\n",
                            "Employee Authorization Failed",
                            JOptionPane.ERROR_MESSAGE);
                    return false;
                }
            }

            return false;
        }
    }

我的用户类:

/**
 *  @author OperatorX© 2013
 */

package dossierIB;

public class User 
{
    private String user;
    private String pass;

    public User(String u, String p)
    {
        user = u;
        pass = p;
    }

    public String getUsername()
    {
        return user;
    }

    public String getPassword()
    {
        return pass;
    }

    public void setUsername(String username)
    {
        this.user = username;
    }

    public void setPassword(String password)
    {
        this.pass = password;
    }

}

3 个答案:

答案 0 :(得分:1)

loginAuthorization()中,你第一次自我回归是真是假。

试试这种方式,

boolean ret = false;

     for(int i = 0; i < users.size(); i++)
                {
                    if(users.get(i).getUsername().compareTo(username) == 0 && users.get(i).getPassword().compareTo(password) == 0)
                    {
                        ret = true;
break;

                    }

                    else
                    {
                        passwordField.setText("");
                        Toolkit.getDefaultToolkit().beep();
                        JOptionPane.showMessageDialog(errorFrame,
                                "Could not authorize employee with given username and password.\n\n" +
                                "Please reenter or contact your system administrator.\n\n",
                                "Employee Authorization Failed",
                                JOptionPane.ERROR_MESSAGE);

                    }
                }

                return ret;

答案 1 :(得分:1)

我认为最好为你的程序使用hashmap。示例代码如下所示

import java.util.HashMap;


public class NewClass {
    public static void main(String[] args)
    {
        HashMap<String,String>unamePass=new HashMap<String, String>();
        unamePass.put("user1", "pass1");
        unamePass.put("user2", "pass2");
        unamePass.put("user3", "pass3");
        unamePass.put("user4", "pass4");
        if(unamePass.get("user1")!=null)
        {
            String password=unamePass.get("user1");
            /*compare password with entered password*/
        }
    }
}

答案 2 :(得分:0)

将else分支移出loginAuthorization()中的for循环。

这样的事情应该有效

    for (int i = 0; i < users.size(); i++) {
        if (users.get(i).getUsername().compareTo(username) == 0 && users.get(i).getPassword().compareTo(password) == 0) {
            return true;
        }
    }
    passwordField.setText("");
    Toolkit.getDefaultToolkit().beep();
    JOptionPane.showMessageDialog(errorFrame,
            "Could not authorize employee with given username and password.\n\n"
            + "Please reenter or contact your system administrator.\n\n",
            "Employee Authorization Failed",
            JOptionPane.ERROR_MESSAGE);
    return false;