如何检查输入的小写字母数的密码?

laik7k3q  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(286)

我使用下面的脚本来检查我的密码长度,大写字母数和数字数。
有没有办法让它同时检查小写字母的数量?我试过几次修改我的代码,但每次都会取消另外两个检查。提前谢谢!

import java.util.*;
public class ValidatePassword {
public static void main(String[] args) {
    String inputPassword;
    Scanner input = new Scanner(System.in);
    boolean success=false;
    while(!success){

    System.out.print("Password: ");
    inputPassword = input.next();
    System.out.println(PassCheck(inputPassword));
    if(PassCheck(inputPassword).equals("Valid Password")) success = true; 
    System.out.println("");

    } 
  }

  public static String PassCheck(String Password) {
    String result = "Valid Password";
    int length = 0;
    int numCount = 0;
    int capCount = 0;
    for (int x = 0; x < Password.length(); x++) {
      if ((Password.charAt(x) >= 47 && Password.charAt(x) <= 58) || (Password.charAt(x) >= 64 && Password.charAt(x) <= 91) ||
        (Password.charAt(x) >= 97 && Password.charAt(x) <= 122)) {
      } else {
        result = "Password Contains Invalid Character!";
      }
      if ((Password.charAt(x) > 47 && Password.charAt(x) < 58)) {
        numCount++;
      }
      if ((Password.charAt(x) > 64 && Password.charAt(x) < 91)) {
        capCount++;
      }

      length = (x + 1);
    }
    if (numCount < 2) {
      result = "digits";
    }
    if (capCount < 2) {
      result = "uppercase letters";
    }
    if (capCount < 2) {
      result = "uppercase letters";
    }
    if (numCount < 2 && capCount < 2) 
    {
      result = "uppercase letters digits";
    }

    if (length < 2) {
      result = "Password is Too Short!";
    }
    return (result);
  }
}
dgtucam1

dgtucam11#

逐个检查每个字符是一项乏味的任务,会增加逻辑错误。您可以使用正则表达式来实现这一点。你修改过的“通行证”method:-

public static String PassCheck(String Password) {
    int length = Password.length();
    if(length<2)
        return "Password is Too Short!";
    String regex = "^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]+$";
    boolean d = Password.replaceAll("[^0-9]", "").length()<2;
    boolean u = Password.replaceAll("[^A-Z]", "").length()<2;
    boolean l = Password.replaceAll("[^a-z]", "").length()<2;
    if(d && u)
        return "digits uppercase";
    else if(l&&u)
        return "lowercase uppercase";
    else if(l&&d)
        return "lowercase digits";
    else if(d)
        return "digits";
    else if(u)
        return "uppercase";
    else if(l)
        return "lowercase";
    else if(!(Password.matches(regex)))
        return "Password contains Invalid Character!";
    return "Valid Password";
}

相关问题