If 语句和用户名/密码

问题描述 投票: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;

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


  }


 }
java if-statement passwords joptionpane
1个回答
0
投票

只要给定的用户名和密码与真实用户名和密码不匹配并且用户仅尝试了少于 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);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.