关于swing:为什么我的密码验证无法使用Java?

Why is my password validation not working Java?

本问题已经有最佳答案,请猛点这里访问。

我的登录屏幕上有一个密码字段。 由于某种原因,当我输入正确的密码" u123"时,即使密码正确,它也会给我带来错误的密码错误消息。 为什么这样做。

我的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            char[] userInput = passwordField.getPassword();
            char[] correctPassword = { 'u', '1', '2', '3'};

            if (userInput.equals(correctPassword)) {
            JOptionPane.showMessageDialog(LoginScreen.this,
                   "Success! You typed the right password.");
            } else {
                JOptionPane.showMessageDialog(LoginScreen.this,
                   "Invalid password. Try again.",
                   "Error Message",
                    JOptionPane.ERROR_MESSAGE);
            }
        }
    });

我知道这可能不是进行密码检查的最佳方法,但我只是一个初学者,并且正尝试进行一些练习。


您的代码有:

1
2
char[] userInput = passwordField.getPassword();
char[] correctPassword = { 'u', '1', '2', '3'};

这是两个不同的字符数组。

因此,此测试返回false:

1
 if (userInput.equals(correctPassword))

而是尝试使用Arrays.equals()方法

1
 if (Arrays.equals(userInput, correctPassword)) { ... }