Java - 为什么我的身份验证程序无法登录...?

时间:2014-05-28 23:59:54

标签: java arrays authentication char login-attempts

好的,我甚至打印出将与用户名和密码进行比较的变量值。 用户名luke 密码:密码 用户名尝试:卢克 密码尝试:[C @ 5e15c325

但是我试图输入密码' .... JPasswordField包含一个字符数组,所以我必须使用' toCharArray'比较char []' passwordAttempt'并且String'传递'保存文件中保存的密码。也许这就是为什么密码尝试是一些奇怪的价值? 这是login()函数的代码:

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 个答案:

答案 0 :(得分:0)

passwordAttempt == pass.toCharArray()

您无法在Java中比较这样的数组。

使用

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

或者将它们转换为字符串并进行比较(也不是使用==!)

passwordAttemptString.equals(pass);