CrystallineLati CrystallineLati - 3 months ago 13
Java Question

How would I program an array of Strings to work as a set of passwords?

So I'm trying to get a java applet to accept a set of multiple passwords, so naturally I thought to put them in array. However, only one of the passwords in the array is working, the last one in the set. None of the ones before it will work and my applet denies the others. This is my code so far:

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


How would I get this to work properly? Am I doing something wrong with the array? Is it something in the code altogether?

Answer

The code is checking each password even if a valid one is found meaning that even if a valid password is found it will still change based on the validity of the next password. So the last one in the array declares the status of grantedPrompt and deniedPrompt. Try adding a break after the input is equal to one of the passwords.

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