-1

I want to find out why the second if statement in this code always returns false, so every time I click the 'go' button in my program it shows incorrect password. Anyone have any ideas?

package Main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

public class CodexConsoleEngine extends CodexConsoleWindow implements ActionListener {  

    public void actionPerformed(ActionEvent e) {
        boolean isPasswordEntered = false;
        JButton clickedButton = (JButton) e.getSource();
        String commandSent;
        String passwordSet = "password";
        char[] charPasswordEntered = password.getPassword();
        String passwordEntered = charPasswordEntered.toString();

        if(!isPasswordEntered){
            if(passwordEntered.equals(passwordSet)){
                consoleOutput.append("Correct password\n");
            }else{
                consoleOutput.append("Incorrect password\n");
            }
    }else{
        consoleOutput.append("You have already entered your password");
    }
}

}

Sorry for any obvious mistakes, I've only started java recently. REALLY recently.

EDIT: I've edited the code to use the .equals() method, but it still doesn't work. Could it have anything to do with the toString() method or the fact that I'm using JPasswordField?

IntrepidPig
  • 110
  • 2
  • 12

3 Answers3

2

Try this:

if(!isPasswordEntered){
        if(passwordEntered.equals(passwordSet)) {
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Hmm, doesn't seem to work. I added in a little extra thing to tell me what the password I entered was read as, and now it's the right password, but it used to be gibberish. However, it still says incorrect password in the consoleOutput field... – IntrepidPig Nov 20 '13 at 00:13
0

To compare Strings use String.equals() method for example in your code it should be if(passwordEntered.equals(passwordSet)) or you can use String.equalsIgnoreCase() to ignore capitalization

chargers2143
  • 101
  • 1
  • 2
  • 4
0

You are incorrectly testing for equality with the Strings passwordEntered and passwordSet.

To correctly testing for equality in Strings use String.equals or String.equalsIgnoreCase for a case insensitive equality test.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64