2016-08-19 19 views
0

所以我试图让一个Java小程序接受一组多个密码,所以很自然地我想把它们放在数组中。但是,阵列中只有一个密码正在工作,即集合中的最后一个密码。没有任何工具可以工作,我的小程序会拒绝其他工具。这是我的代码到目前为止:我该如何编程一个字符串数组来作为一组密码工作?

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

即使有匹配,您仍循环所有密码。因此,如果密码匹配时更改代码以返回方法。

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); 

    } 
相关问题