简体   繁体   中英

Compare User Input and Initialized Array from JFrame Form JAVA

I was working on a login form using JAVA. I get it to worked but no matter what I input, it will link to another JFrame and in the same time come out with the error message, no matter what I input is in the initialized array or not. Is it my loop for checking is wrong? Hope someone can help, thanks!

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

public class Login extends javax.swing.JFrame {
private String [] loginid = {"1001","1002","1003","1004","1005"};
private String [] password = {"abc1","abc2","abc3","abc4","abc5"};

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  for(int times=0;times<loginid.length;times++)
  {
      for(int count=0;count<password.length;count++){
      loginid[times]=jTextField1.getText();
      password[times]=jPasswordField1.getText();

      if(loginid[times]==loginid[count] && password[times]==password[count])
      {
          jTextField1.setText("");
          jPasswordField1.setText("");
          this.setVisible(false);
          new FrontPage().setVisible(true);
      }
      else
         JOptionPane.showMessageDialog(null, "Information invalid. Please try again.");
         this.setVisible(false);
      }
  }
}    

I do the coding in the LOGIN button.

Thanks.

I don't understand your nested loops. Something like this:

private int failedAttempts = 0;    

public void tryLogin() {
    final String username = jTextField1.getText();
    final String password = jPasswordField1.getText();

    // if (failedAttempts >= 3) ...

    if (loginOK(username, password)) {
        jTextField1.setText("");
        jPasswordField1.setText("");
        this.setVisible(false);
        new FrontPage().setVisible(true);
    }
    else {
        if (++failedAttempts >= 3) {
            JOptionPane.showMessageDialog(null, "Too many errors. bye.");
            System.exit(0); // or something
        }

        JOptionPane.showMessageDialog(null, "Information invalid. Please try again.");
        this.setVisible(false);
    }
}

public boolean isLoginOK(String username, String password) {
    for (int i=0; i<loginid.length; i++)
        if (username.equals(loginid[i]) && password.equals(password[i]))
            return true;

    return false;
}

Of course you are storing plain passwords in memory, but I assume this application doesn't need outstanding security...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM