Thomas
Thomas

Reputation: 65

How to correctly do a while loop for passwords

I am trying to make a register Jframe window that collects usernames and passwords right now I am trying to create a condition if the password is not equal to the confirm password field have the user type in a new pass code that matches. I keep getting spammed with the Jpane error message and it wont go away after I typed the passwords in incorrectly.

I have tried for loops, Do while loops and regular while loops. I have tried a few things

This is just creating the JLabel

  JLabel Register = new JLabel("Register");

This next part is making the Jlabel interactive with the user

  Register.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
  Register.addMouseListener(new MouseAdapter() {

  @Override
  public void mouseClicked(MouseEvent e) {

When Register is clicked a few things will happen.

These are 4 variables I created to keep track of the user input.

   String password = passwordField.getText();
   String confirmpass = passwordField_1.getText();
   String name =  userName.getText();       
   String email = createEmail.getText();

This is where I start the do while loop to confirm if the passwords match or not and I i will have it repeat

  do {  
      JOptionPane.showMessageDialog(null, "Passwords do not match", "Login Error", JOptionPane.ERROR_MESSAGE);
        password = "";
        confirmpass = "";

  }while(password == confirmpass);
  dispose();

  //System.out.println("Testing the Register Button lol or label " + name);

}

I want to be able to have a condition that makes sure the passwords match before exiting the screen. Also if possible could some show me a way to store the user input from the JFrame into an Array.

Upvotes: 0

Views: 295

Answers (1)

NJY404
NJY404

Reputation: 358

Replace your do-while loop with if statement instead

//inside onclick function
if(!confirm_pass.equals(password)){
    JOptionPane.showMessageDialog(null, "Passwords do not match", "Login Error", 
    JOptionPane.ERROR_MESSAGE);
    return; //the return keyword will stop the method to go further.
}


dispose();

the do-while loop will be pointless if the passwords are not the same, as they will only loop endlessly. Also you should use the equals() method when comparing strings than using ==.

Upvotes: 1

Related Questions