-2

Okay, so I even printed out the values of the variables that will be compared to the username and password. Username luke Password: password Username Attempt: luke Password Attempt: [C@5e15c325

But I'm attempting to input 'password'.... The JPasswordField holds a character array, so I have to use the 'toCharArray' when comparing the char [] 'passwordAttempt' and the String 'pass' that holds the password that is held in a file. Maybe this is why the password attempt is some strange value? Here's the code of the login() function:

public void login() {

   //booleans for error-handling and user authentication

    boolean usersInDatabase = true;
    boolean userAuthentication = false;
    boolean passwordAuthentication = false;
    //create the data reader
    try {
         reader = new Scanner(user1); //user1 is a file
    } catch (FileNotFoundException noUsers) {
        JOptionPane.showMessageDialog(window, "No users in the database");
        usersInDatabase = false;
    }


    //variables

    String user = "";          //variables that will hold the file data which has the 
    String pass = "";          //username and password
    try {
     user = reader.nextLine();   
     pass = reader.nextLine();
    }
    //you can skip through the error-handling
    catch (NoSuchElementException noUsers) {
        JOptionPane.showMessageDialog(window, "No users in the database");
        usersInDatabase = false;
    }
    if (usersInDatabase)
    {

    String userAttempt = usernameField.getText();
    String message = ""; //message to display if authentication is unsuccessful
    char[] passwordAttempt = passwordField.getPassword();
    //okay -- important stuff
    //username authentication


    if (userAttempt == user) {
        userAuthentication = true; 
    }
    else 
    message += "Incorrect Username -- ";


    //password authentication


if (passwordAttempt == pass.toCharArray()) {        //check to see if the input matches the string (a character array) that has the value of the file
    passwordAuthentication = true; 
}
else 
message += "Incorrect Password";



if (passwordAuthentication == true && userAuthentication == true)
{
      JOptionPane.showMessageDialog(window, "Authorization Successful");
      cards.show(cardPanel, "documents");
}
else if(passwordAuthentication == false && userAuthentication == false)
    JOptionPane.showMessageDialog(window, message);


     //to print out the values for debugging
System.out.println("Username " + user + "\nPassword: " + pass + "\nUsername Attempt: " + userAttempt + "\nPassword Attempt: " + passwordAttempt);
}

}

1 Answers1

0
passwordAttempt == pass.toCharArray()

You cannot compare arrays like this in Java.

Use

Arrays.equals(passwordAttempt, pass.toCharArray());

Or convert them to Strings and compare those (also not by using ==!)

passwordAttemptString.equals(pass);
Thilo
  • 257,207
  • 101
  • 511
  • 656