当用户输入的密码不合法时,如何终止程序?



我是java编程的新手,当用户输入不是有效密码时,我如何终止我的程序?

这是我的代码有一个问题

final int MAX = 8;
    final int MIN_Uppercase = 1;
    final int NUM_Digits = 1;
    final int Special = 1;
    
    int invalidCount = 0;
    int uppercaseCounter = 0;
    int digitCounter = 0;
    int specialCounter = 0;
    int spaceCounter = 0;
    
    Scanner sc = new Scanner (System.in);
    
    System.out.println ("Enter Name: ");
    String name = sc.nextLine();
    int spacePosition = name.indexOf(" ");
    
    System.out.print ("n");
    
    System.out.println ("Enter Birthday (MM DD YYYY): ");
    String birthday = sc.nextLine();
    
    System.out.print ("n");
    
    System.out.println ("Enter password: ");
    Scanner input = new Scanner (System.in);
    
    String password = input.nextLine();
        
        for (int i = 0; i < password.length(); i ++)
        {
          char c = password.charAt(i);
          
          if (Character.isUpperCase(c))
            uppercaseCounter ++;
          
          if (c == ' ')
            spaceCounter ++;
          
          if (c == '$' || c == '#' || c == '?' || c == '!' || c == '_' || c == '=' || c == '%' || c == '.')
            specialCounter ++;
          
          else if (Character.isDigit(c))
            digitCounter ++;
        }
    if (password.length() >= MAX && uppercaseCounter >= MIN_Uppercase && specialCounter == 1 && digitCounter == 1)
    {
      System.out.println(" ");
      
      System.out.println ("n");
    }
    else
    {
      
      if (password.length() < MAX)
        System.out.println("Enter atleast 8 characters");
      
      if (spaceCounter > 0)
        System.out.println("Password contains whitespaces");
      
      if (uppercaseCounter < MIN_Uppercase)
        System.out.println("Enter atleast 1 Uppercase Character");
      
      if (digitCounter < 1)
        System.out.println("Enter atleast 1 digit");
      
      if (specialCounter < 1)
        System.out.println("Enter atleast 1 special character");
      
      System.out.print ("n");
      
      
    }
    
    System.out.println ("Your login details");
    System.out.print ("n");
    
    System.out.println ("Name    : " + name);
    System.out.println ("Birthday: " + birthday);
    System.out.println ("Username: " + name.substring(0, 2) + name.substring(spacePosition + 3) + birthday.substring(3,5));
    System.out.println ("Password: " + password);

问题是当用户输入无效密码时,进程将继续打印登录详细信息。

我想知道如何终止程序或返回输入密码。

如果密码有效,则打印详细信息;如果密码无效,则程序将循环返回请求密码,否则程序将终止。

我建议使用WHILE循环来包含用户输入密码的代码部分。您可以使用一个变量来跟踪密码是否有效,或者跟踪用户通过循环的次数,并在某些条件下跳出循环。

PSEUDO CODE:
int ntimes = 0;
boolean isValid = false;
while(isValid == false){
  //Prompt for Password
  //User Enters Password
  if(password is valid){
    isValid = true;
  }
  else{
   ntimes++;
  }
  if(ntimes == 7) break;
}
if(isValid == false){
  "You entered a bad password too many times."
  QUIT
}

最新更新