我正在处理一个注册表单项目。该表单要求用户在JPassword字段中输入他们选择的密码,并在另一个JPassword字段中再次输入。
我使用JOptionPane提示用户如果两个密码不匹配。但是当我在这两个字段上使用passwordField.getPassword().toString()时,它们不匹配。我尝试在两个字段上都输入基本的“12345”,但仍然没有成功。
我知道应该使用.equals(),但是“不等于”的等价物是什么,而不使用“!=”运算符。
以下是代码示例:
任何关于这个问题的帮助都将不胜感激。
我使用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