java - 如何检查输入的小写字母数量的密码?
问题描述
我正在使用下面的脚本来检查我的密码长度、大写字母数量和位数。
有没有办法让它也检查小写字母的数量?我试图修改我的代码几次,但每次我这样做都会踢出另外两个检查。提前致谢!
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);
}
}
解决方案
逐个检查每个字符是一项繁琐的任务,并且会增加您的逻辑错误。您可以为此使用正则表达式。您修改后的“PassCheck”方法:-
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";
}
推荐阅读
- vuejs2 - 如何重置 Vuetify 表单但仍保持选中 v-select?
- python - 使用与垂直线不同的符号
- postgresql - Postgres用双引号将字符串拆分为多行?
- date - 如何用“openingHours”表示类似的连续和非连续天?
- html - Bootstrap Carousel 不切换图像
- javascript - 业力黄瓜配置
- javascript - 在没有付费版本的地图中显示我在路线中的自定义点
- pandas - 如何更快地使用 pandas 计算 groupby 滚动统计信息?
- python - 卷积自动编码器未在 (62,47,1) 数据集上进行训练,“预期形状错误”
- excel-formula - VLOOKUP 在公式中使用“False”时返回 #N/A,而不是添加“False”返回随机值