如何在Java中比较两个密码?

3
我正在处理一个注册表单项目。该表单要求用户在JPassword字段中输入他们选择的密码,并在另一个JPassword字段中再次输入。
我使用JOptionPane提示用户如果两个密码不匹配。但是当我在这两个字段上使用passwordField.getPassword().toString()时,它们不匹配。我尝试在两个字段上都输入基本的“12345”,但仍然没有成功。
我知道应该使用.equals(),但是“不等于”的等价物是什么,而不使用“!=”运算符。
以下是代码示例:
    if(e.getSource() == submit)
    {   
        String name = nameTextField.getText();
        String address = addressTextField.getText();
        String phoneNumber = numberTextField.getText();
        String dob = datePicker.getDateFormatString();
        String password = passwordField.getPassword().toString();
        String password2 = passwordFieldTwo.getPassword().toString();


        try
        {
            //If the user leaves the field empty
            if(name == null || address == null || phoneNumber == null || dob == null 
                || password == null || password2 == null)
            {
                //Error message appears to prompt the user to 
                //complete the form
                JOptionPane.showMessageDialog(null, "All fields must be complete to submit.", "Woops", JOptionPane.ERROR_MESSAGE);
            }

            if(password != password2)
            {
                    JOptionPane.showMessageDialog(null, "Passwords do not match.", "Woops", JOptionPane.ERROR_MESSAGE);
                    passwordField.setText(null);
                    passwordFieldTwo.setText(null);
            }

任何关于这个问题的帮助都将不胜感激。

passwordField.getPassword() 返回一个字符数组。调用 toString() 不会将密码作为字符串返回。你可以通过 new String(); 转换为字符串,但不应该这样做。它以 char 数组而不是 String 的形式返回有其原因。请阅读此问题:https://dev59.com/rGox5IYBdhLWcg3w74q2 - Madhawa Priyashantha
关于您在问题被标记为重复后的编辑:只需在.equals()的结果上使用!即可获得类似于!=的行为。 - Matt
1个回答

2

!=equals()用于字符串比较时的区别在于使用!x.equals(y)

举个例子,如果要检查两个密码匹配,请执行以下操作:

if (!Arrays.equals(passwordField.getPassword(), passwordFieldTwo.getPassword())) {
   JOptionPane.showMessageDialog(null, "Passwords do not match.", "Woops", JOptionPane.ERROR_MESSAGE);
} 

1
这对我有用。使用以下内容确保密码匹配且不为空:if(!Arrays.equals(passwordField.getPassword(),passwordFieldTwo.getPassword())&& passwordField.getPassword()!= null && passwordFieldTwo.getPassword()!= null) - Aaronward
@Aaronward 很高兴听到这个消息,你能接受我的答案并点赞吗?这样其他看到这个问题的人就知道这个答案是正确的。 - M. Suurland

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接