0

I have a password field in my login screen. For some reason when i type in the correct password which is "u123" it gives me the incorrect password error message even though it is correct. Why is it doing this.

The code i have below:

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);
            }
        }
    });

I know this may not be the best way of doing the password check but I'm just a beginner and just trying to get some practice.

user982467
  • 142
  • 8
  • Why don't you use strings instead of character arrays? – Thomas May 16 '17 at 12:27
  • @Thomas Strings for passwords are [bad](http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords?rq=1). – Jure Kolenko May 16 '17 at 12:29
  • If you use `char []`, can you try using `Arrays.equals`? There is an example [here](https://docs.oracle.com/javase/tutorial/uiswing/components/passwordfield.html) – Stuti Rastogi May 16 '17 at 12:30
  • @user982467 sure it can be. But it shouldn't be. See [this discussion](http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords?rq=1) – eis May 16 '17 at 12:55

1 Answers1

3

Your code has :

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

It's two different arrays of characters.

So this test returns false :

 if (userInput.equals(correctPassword))

Instead, try to use the Arrays.equals() method

 if (Arrays.equals(userInput, correctPassword)) { ... }
Prim
  • 2,880
  • 2
  • 15
  • 29
  • I tried that and i get error saying Cannot make a static reference to the non-static method equals(Object) from the type Object – user982467 May 16 '17 at 12:48
  • 1
    Ok it works now. I changed it to `if (Arrays.equals(userInput, correctPassword))` . Thx – user982467 May 16 '17 at 12:50
  • @Prim indeed you meant `if (Arrays.equals(userInput, correctPassword))`. `Arrays.equals(userInput.equals(correctPassword))` makes no sense – eis May 16 '17 at 12:56
  • Yep, true. My bad. it's fixed. – Prim May 16 '17 at 16:42