2016-08-19 4 views
0

그래서 여러개의 패스워드를 받아들이 기 위해 자바 애플릿을 얻으려고합니다. 그래서 자연스럽게 배열에 넣을 생각이었습니다. 그러나 어레이의 암호 중 하나만 작동하며 세트의 마지막 암호는 작동합니다. 그 전에는 아무 것도 작동하지 않고 애플릿은 다른 것을 거부합니다. 지금까지 내 코드 :일련의 암호로 작동하도록 문자열 배열을 프로그래밍하는 방법은 무엇입니까?

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class JPasswordC extends JApplet implements ActionListener 
{ 
private final String[] password = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"}; 

private Container con = getContentPane(); 
private JLabel passwordLabel = new JLabel("Password: "); 
private JTextField passwordField = new JTextField(16); 

private JLabel grantedPrompt = new JLabel("<html><font color=\"green\">Access Granted</font></html>"); 
private JLabel deniedPrompt = new JLabel("<html><font color=\"red\">Access Denied</font></html>"); 

public void init() 
{ 
    con.setLayout(new FlowLayout()); 

    con.add(passwordLabel); 
    con.add(passwordField); 
    con.add(grantedPrompt); 
    grantedPrompt.setVisible(false); 
    con.add(deniedPrompt); 
    deniedPrompt.setVisible(false); 

    passwordField.addActionListener(this); 
} 

public void actionPerformed(ActionEvent ae) 
{ 
    String input = passwordField.getText(); 

    for(String p : password) 
    { 

     if(input.equalsIgnoreCase(p)) 
     { 
      grantedPrompt.setVisible(true); 
      deniedPrompt.setVisible(false); 
     } 
     else 
     { 
      grantedPrompt.setVisible(false); 
      deniedPrompt.setVisible(true); 
     } 
    } 
} 
} 

어떻게하면 제대로 작동합니까? 배열에 문제가 있습니까? 코드에 모두 포함되어 있습니까?

답변

0

유효한 암호가 발견 되더라도 다음 암호의 유효성을 기반으로 변경되는 코드입니다. 따라서 배열의 마지막 요소는 grantedPromptdeniedPrompt의 상태를 선언합니다. 입력이 암호 중 하나와 같으면 break을 추가하십시오.

for(String p : password) 
{ 

    if(input.equalsIgnoreCase(p)) 
    { 
     grantedPrompt.setVisible(true); 
     deniedPrompt.setVisible(false); 
     break; // break out or loop once found 
    } 
    else 
    { 
     grantedPrompt.setVisible(false); 
     deniedPrompt.setVisible(true); 
    } 
} 
0

당신은 match.So 적 암호 일치가있을 때 방법을 반환하는 코드를 변경할 수있다하더라도, 모든 암호를 통해 반복된다.

public void actionPerformed(ActionEvent ae) 
    { 
     String input = passwordField.getText(); 

     for(String p : password) 
     { 

      if(input.equalsIgnoreCase(p)) 
      { 
       grantedPrompt.setVisible(true); 
       deniedPrompt.setVisible(false); 
       return; 
      } 

     } 
     grantedPrompt.setVisible(false); 
     deniedPrompt.setVisible(true); 

    }