我在我的登录屏幕上有一个密码字段。由于某种原因,当我输入正确的密码“u123”时,即使它正确,它也会给我提供不正确的密码错误消息。它为什么这样做。为什么我的密码验证不工作Java?
代码中,我有以下:
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);
}
}
});
我知道这可能不是做密码检查的最佳方式,但我只是一个初学者,只是想获得一些实践。
你为什么不使用字符串代替字符数组? – Thomas
@Thomas字符串的密码是[bad](http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords?rq=1)。 –
如果你使用'char []',你能尝试使用'Arrays.equals'吗?有一个例子[这里](https://docs.oracle.com/javase/tutorial/uiswing/components/passwordfield.html) –