2016-03-22 81 views
2

我正在使用註冊表單進行項目。該表單會要求用戶輸入他們在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); 
      } 

任何幫助,這將不勝感激。

+0

'passwordField .getPassword()'返回一個字符數組.calling'toString()'不會給你一個字符串的密碼。你可以通過'new String();'將字符串轉換爲字符串,但是你不應該將它作爲'char數組'而不是'String'返回。請閱讀這個問題http://stackoverflow.com/questions/8881291 /爲什麼是char-preferred-over-string-for-passwords-in-java –

+0

至於你在編輯問題後被標記爲重複:**只需使用'!'結果的'.equals ()'得到'!='的行爲** – Matt

回答

1

的相關equals()用於字符串比較!=!x.equals(y)

表示作爲一個例子讓我們你的代碼,看看這兩個密碼比賽做到以下幾點:

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

這對我有用。使用以下命令來確認密碼匹配,也沒有留下空 如果(!滿足Arrays.equals(passwordField.getPassword(),passwordFieldTwo.getPassword())&& \t \t \t \t \t passwordField.getPassword()!= NULL && passwordFieldTwo.getPassword()!= null) – Aaronward

+0

@Aononward很好聽,你能接受我的回答並且贊成嗎?然後看到這個問題的其他人知道這個答案是正確的 –