2017-05-16 34 views
0

我在我的登录屏幕上有一个密码字段。由于某种原因,当我输入正确的密码“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); 
      } 
     } 
    }); 

我知道这可能不是做密码检查的最佳方式,但我只是一个初学者,只是想获得一些实践。

+0

你为什么不使用字符串代替字符数组? – Thomas

+0

@Thomas字符串的密码是[bad](http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords?rq=1)。 –

+0

如果你使用'char []',你能尝试使用'Arrays.equals'吗?有一个例子[这里](https://docs.oracle.com/javase/tutorial/uiswing/components/passwordfield.html) –

回答

3

您的代码有:

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

这两个字符不同的阵列。

因此本次测试返回false:

if (userInput.equals(correctPassword)) 

相反,尝试使用Arrays.equals()方法

if (Arrays.equals(userInput, correctPassword)) { ... } 
+0

我试过,我得到错误说不能做一个静态引用的非静态方法等于(对象)类型对象 – user982467

+1

好吧,它现在的作品。我将它改为'if(Arrays.equals(userInput,correctPassword))'。 Thx – user982467

+0

@Prim的确你的意思是如果(Arrays.equals(userInput,correctPassword))'。 'Arrays.equals(userInput.equals(correctPassword))'没有意义 – eis