如果声明和用户名/密码

时间:2016-04-03 23:56:26

标签: java if-statement passwords joptionpane username

我希望我的程序提示用户输入设置的用户名和密码。如果凭据不匹配,我希望它循环,直到它们正确或超过尝试次数。

例如,如果他们的“用户名”错误,程序应继续询问用户“用户名”,直到他们获得正确的用户名或他们达到5次尝试

   import javax.swing.JOptionPane;

   public class Password_DiljotJ_R1 {

  public static void main(String[] args) {

  int attempt = 0;

String username = "john";
String password = "123"; 
String usernameEntered;
String passwordEntered;

usernameEntered = (JOptionPane.showInputDialog("Please enter the username"));
passwordEntered = (JOptionPane.showInputDialog("Please enter the password"));

 if (usernameEntered.equals(username) && passwordEntered.equals(password) ){

     JOptionPane.showMessageDialog(null,"Credentials Match. Welcome John!");    
}



 else if (usernameEntered.equals(username)) {

    JOptionPane.showMessageDialog(null,"Password Invalid.");
    attempt++;
    passwordEntered = (JOptionPane.showInputDialog("Please enter the password AGAIN"));

    }

else if (passwordEntered.equals(password)) {

    JOptionPane.showMessageDialog(null, "Username Invalid.");
    attempt++;
    usernameEntered = (JOptionPane.showInputDialog("Please enter username AGAIN"));
}

else {

    JOptionPane.showMessageDialog(null,"Both username and password are inncorrect. Who are you");
    attempt++;
    usernameEntered = (JOptionPane.showInputDialog("Please enter username AGAIN"));
    passwordEntered = (JOptionPane.showInputDialog("Please enter password AGAIN"));
}
    if (attempt == 5){

   JOptionPane.showMessageDialog(null,"You've reached maximum attempts. Program will now close");
   }


  }


 }

1 个答案:

答案 0 :(得分:-1)

以下代码段将请求输入用户名和密码,只要给定的用户名和密码与实际用户名和密码不匹配,并且用户尝试的次数少于5次。

import javax.swing.JOptionPane;

public class Password_DiljotJ_R1 {

    public static void main(String[] args) {

        int attempt = 0;
        String username = "john";
        String password = "123";
        String usernameEntered;
        String passwordEntered;

        do {
            usernameEntered = (JOptionPane.showInputDialog("Please enter the username"));
            passwordEntered = (JOptionPane.showInputDialog("Please enter the password"));
            attempt++;
        } while (usernameEntered != username && passwordEntered != password && attempt < 5);
    }

}