【问题标题】:How to compare 2 passwords in java? [duplicate]如何比较java中的2个密码? [复制]
【发布时间】:2016-07-09 13:38:18
【问题描述】:

我正在处理一个带有注册表单的项目。表单要求用户 在 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 array 而不是String 返回。阅读此问题stackoverflow.com/questions/8881291/…
  • 问题被标记为重复后的编辑:只需在.equals() 的结果上使用! 即可获得与!= 相似的行为。

标签: java passwords jpasswordfield


【解决方案1】:

用于String比较的equals()相关的!=!x.equals(y)表示

举个例子,让您的代码查看两个密码是否 not 匹配,请执行以下操作:

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

【讨论】:

  • 这对我有用。使用以下来确保密码匹配并且不为空 if (!Arrays.equals(passwordField.getPassword(), passwordFieldTwo.getPassword()) && passwordField.getPassword() != null && passwordFieldTwo.getPassword() !=空)
  • @Aaronward 很高兴听到,你能接受我的回答并投票吗?那么看到这个问题的其他人就知道这个答案是正确的
猜你喜欢
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
  • 2011-02-05
相关资源
最近更新 更多