2017-05-16 1 views
0

로그인 화면에 비밀번호 입력란이 있습니다. 어떤 이유로 올바른 암호를 "u123" 입력 할 때 올바른 암호 오류 메시지를 내게 제공합니다. 왜 이렇게하고있는거야?비밀번호 유효성 검사가 Java가 작동하지 않는 이유는 무엇입니까?

코드 나는 아래에 있습니다

btnLogin = new JButton("Login"); 
btnLogin.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      char[] userInput = passwordField.getPassword(); 
      char[] correctPassword = { 'u', '1', '2', '3'}; 

      if (userInput.equals(correctPassword)) { 
      JOptionPane.showMessageDialog(LoginScreen.this, 
        "Success! You typed the right password."); 
      } else { 
       JOptionPane.showMessageDialog(LoginScreen.this, 
        "Invalid password. Try again.", 
        "Error Message", 
        JOptionPane.ERROR_MESSAGE); 
      } 
     } 
    }); 

나는이 암호 검사를하는 가장 좋은 방법하지 않을 수 있습니다 알고 있지만 난 그냥 초보자이야 그냥 연습을 시도.

+0

왜 대신 문자 배열의 문자열을 사용하지 않는 Arrays.equals() 방법을 사용하려고? – Thomas

+0

@Thomas 암호 용 문자열은 [bad]입니다 (http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-st-for-passwords?rq=1). –

+0

'char []'을 사용하면'Arrays.equals'를 사용해 볼 수 있습니까? 여기 [https://docs.oracle.com/javase/tutorial/uiswing/components/passwordfield.html] 예가 있습니다. –

답변

3

코드는 있습니다

char[] userInput = passwordField.getPassword(); 
char[] correctPassword = { 'u', '1', '2', '3'}; 

그것은 문자의 두 개의 서로 다른 배열입니다.

그래서이 테스트는 false를 반환 :

if (userInput.equals(correctPassword)) 

대신

if (Arrays.equals(userInput, correctPassword)) { ... } 
+0

나는 그것을 시도하고 오류가 얻을 수 없다. 비 정적 메서드에 대한 정적 참조가 Object 유형에서 (Object)와 같습니다. – user982467

+1

이제는 작동합니다. if (Arrays.equals (userInput, correctPassword))로 변경했습니다. Thx – user982467

+0

@Prim 실제로 if (Arrays.equals (userInput, correctPassword))를 의미합니다. 'Arrays.equals (userInput.equals (correctPassword))'는 의미가 없습니다 – eis

관련 문제