-3

I am a noob java programmer trying to complete an assignment in an online class. I mention this specifically because the course material has not covered comparing strings this way, and the professor has not responded to my emails.

I need to get user input for a username and password, and return a result if both are correct. I have looked at Oracle's Password Fields and a similar question on here comparing one input to one array as well as several other help posts that have come up in my google searches.

My current code will return correct if I enter the first name and password, but when I attempt the second one it does not return a result at all. It will also return true even if only one input value is correct when both need to be. Per the assignment I am using a swing application so I'll post the relevant code first and then the whole thing below it to hopefully avoid confusion.

Any help on what I'm missing would be greatly appreciated.

Trouble Part:

// get the values entered by the user
String str1 = name1.getText();
String str2 = pass1.getText();
//create my user info strings
String[] userNameArray = {
  "Vale.Vicky",
  "Lane.Lois",
  "Kent.Clark",
  "Wayne.Bruce",
  "Parker.Peter",
  "Rogers.Steve",
  "Luther.Lex",
  "Osborn.Harry",
  "Prince.Diana",
  "Admin"
};
String[] passwordArray = {
  "BatmanFan1",
  "SuperBoyFan1",
  "Kryptonite1",
  "Batman1",
  "SpiderMan1",
  "CtAmerica1",
  "Letitia1",
  "NewGoblin1",
  "WonderWoman1",
  "Password1"
};

boolean check = true;

//Test for matching user name
while (true) {
  for (String i: userNameArray) {
    if (str1.equals(i)) {
      checked.setText("Valid Login");
      check = false;
      break;
    }
  }
  //Test for matching password
  for (String j: passwordArray) {
    if (str2.equals(j)) {
      checked.setText("Valid Login");
      check = false;
      break;
    }
  }
  //return if both false
  if (check) {
    checked.setText("Invalid Login, Try Again");
    continue;
  }
  break;
}
}

Whole Project Code:

/**
 *Rai Duffy
 *Code Creation, Troubleshooting, and Validation Tests
 */

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Font;

public class logInChecker {

  private JFrame frmWeek;
  private JTextField pass1;
  private JTextField checked;
  private JButton btnHelp;
  private JTextField name1;

  /**
   * Launch the application.
   */
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        try {
          logInChecker window = new logInChecker();
          window.frmWeek.setVisible(true);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }

  /**
   * Create the application.
   */
  public logInChecker() {
    initialize();
  }

  /**
   * Initialize the contents of the frame.
   */
  private void initialize() {
    frmWeek = new JFrame();
    frmWeek.getContentPane().setBackground(new Color(51, 204, 153));
    frmWeek.setTitle("Week 5 - Interactive Assignment");
    frmWeek.setBounds(100, 100, 450, 300);
    frmWeek.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmWeek.getContentPane().setLayout(null);

    JLabel lblEnterYourUser = new JLabel("Enter Your User Name:");
    lblEnterYourUser.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblEnterYourUser.setBounds(28, 36, 171, 31);
    frmWeek.getContentPane().add(lblEnterYourUser);

    name1 = new JTextField();
    name1.setColumns(10);
    name1.setBounds(28, 68, 179, 33);
    frmWeek.getContentPane().add(name1);

    JLabel lblEnterYourPassword = new JLabel("Enter Your Password:");
    lblEnterYourPassword.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblEnterYourPassword.setBounds(28, 112, 179, 14);
    frmWeek.getContentPane().add(lblEnterYourPassword);

    pass1 = new JTextField();
    pass1.setBounds(28, 137, 179, 31);
    frmWeek.getContentPane().add(pass1);
    pass1.setColumns(10);

    JButton btnCheck = new JButton("Attempt Login");
    btnCheck.setBackground(new Color(204, 102, 153));
    btnCheck.setFont(new Font("Tahoma", Font.BOLD, 11));
    btnCheck.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        //define what we are looking for

        // get the values entered by the user
        String str1 = name1.getText();
        String str2 = pass1.getText();
        //create my user info strings
        String[] userNameArray = {
          "Vale.Vicky",
          "Lane.Lois",
          "Kent.Clark",
          "Wayne.Bruce",
          "Parker.Peter",
          "Rogers.Steve",
          "Luther.Lex",
          "Osborn.Harry",
          "Prince.Diana",
          "Admin"
        };
        String[] passwordArray = {
          "BatmanFan1",
          "SuperBoyFan1",
          "Kryptonite1",
          "Batman1",
          "SpiderMan1",
          "CtAmerica1",
          "Letitia1",
          "NewGoblin1",
          "WonderWoman1",
          "Password1"
        };

        boolean check = true;

        //Test for matching user name
        while (true) {
          for (String i: userNameArray) {
            if (str1.equals(i)) {
              checked.setText("Valid Login");
              check = false;
              break;
            }
          }
          //Test for matching password
          for (String j: passwordArray) {
            if (str2.equals(j)) {
              checked.setText("Valid Login");
              check = false;
              break;
            }
          }
          //return if both false
          if (check) {
            checked.setText("Invalid Login, Try Again");
            continue;
          }
          break;
        }
      }
    });
    btnCheck.setBounds(238, 136, 171, 32);
    frmWeek.getContentPane().add(btnCheck);

    JLabel lblYesOrNo = new JLabel("Checked Result:");
    lblYesOrNo.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblYesOrNo.setBounds(189, 194, 113, 14);
    frmWeek.getContentPane().add(lblYesOrNo);

    checked = new JTextField();
    checked.setBounds(135, 219, 188, 31);
    frmWeek.getContentPane().add(checked);
    checked.setColumns(10);

  }
}
Community
  • 1
  • 1
  • Why aren't you using any kind of User object to encapsulate usernames and passwords together? – Makoto Apr 11 '17 at 04:17
  • Why are you making a `while (true)` cycle that will execute once? Don't call `setBounds(...)` and use `null` layout. See [null layout is evil](http://www.fredosaurus.com/notes-java/GUI/layouts/nulllayout.html) and the answers in [this question](http://stackoverflow.com/questions/6592468/why-is-it-frowned-upon-to-use-a-null-layout-in-swing) for more information. Why is your user writing their password in a `JTextField` instead of a `JPasswordField`? You should work towards the model and store user and password in a single object which stores both values, then compare through this object – Frakcool Apr 11 '17 at 04:22
  • So...search the user list, for each match find the corresponding password from the password list and compare that, if they are the same, great, if not, keep going. Essentially, you only need to search one list – MadProgrammer Apr 11 '17 at 04:23
  • Also don't make infinite loops in an ActionListener, that could freeze your app and make it irresponsive. And follow the [Java Naming Conventions](http://www.oracle.com/technetwork/java/codeconventions-135099.html) so your code is more readable and understandable to you and us – Frakcool Apr 11 '17 at 04:25

1 Answers1

0

So, based on what I can see, there is a direct correlation between the userNameArray and passwordArray, meaning that the value at n in the userNameArray corresponds to the value at n in the passwordArray

This means your entire search can be boiled down to a single if statement...

for (int index = 0; index < userNameArray.length; index++) {
    if (str1.equals(userNameArray[index]) && str2.equals(passwordArray[index])) {
        return true;
    }
}
return false

Now, having said, it would be SO much simpler if you have some kind of plain old Java object (POJO) which encapsulated the username and password it could then provide validation functionality

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thank you (and everyone else) for the direction. I ended up adding the strings to a hashmap and implementing a version of your simplified for statement. – R.c. Duffy Apr 11 '17 at 06:35