我正在使用註冊表單進行項目。該表單會要求用戶輸入他們在JPassword字段中選擇的密碼,並在另一個JPassword字段中再次輸入該密碼。如何比較java中的2個密碼?
我正在使用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()'返回一個字符數組.calling'toString()'不會給你一個字符串的密碼。你可以通過'new String();'將字符串轉換爲字符串,但是你不應該將它作爲'char數組'而不是'String'返回。請閱讀這個問題http://stackoverflow.com/questions/8881291 /爲什麼是char-preferred-over-string-for-passwords-in-java –
至於你在編輯問題後被標記爲重複:**只需使用'!'結果的'.equals ()'得到'!='的行爲** – Matt