【发布时间】: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