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);
            }

对此的任何帮助将不胜感激。

4

1 回答 1

2

!=equals()字符串比较相关的表示为作为!x.equals(y)

示例,让我们以您的代码为例,查看两个密码是否匹配,请执行以下操作:

if (!Arrays.equals(passwordField.getPassword(), passwordFieldTwo.getPassword())) {
   JOptionPane.showMessageDialog(null, "Passwords do not match.", "Woops", JOptionPane.ERROR_MESSAGE);
} 
于 2016-03-22T15:18:38.373 回答