3 回答
TA贡献1824条经验 获得超5个赞
boolean尝试从方法返回状态checkPass并在方法中放置一个 while 循环main,状态将是您正在检查的条件。
这样,如果输入的字符串通过验证,您可以中断 while 循环,否则循环将继续要求有效输入String:
public static void main(String[] args) throws Exception {
Scanner scn = new Scanner(System.in);
String name = scn.nextLine();
while(checkPass(name)){
name = scn.nextLine();
}
}
// If the boolean retuned from this method is false it will break the while loop in main
public static boolean checkPass(String str) {
int toul = str.length();
int normalLower = 0;
int normalUpper = 0;
int number = 0;
int special = 0;
for (int i = 0; i < toul; i++) {
String s = String.valueOf(str.charAt(i));
if (s.matches("^[a-z]*$")) {
normalLower++;
} else if (s.matches("^[A-Z]*$")) {
normalUpper++;
} else if (s.matches("^[0-9]*$")) {
number++;
} else {
special++;
}
}
System.out.println("normalupper " + normalUpper);
System.out.println("normallower " + normalLower);
System.out.println("number" + number);
System.out.println("special " + special);
return normalLower == 0 || normalUpper == 0 || number == 0 || special == 0;
}
TA贡献1943条经验 获得超7个赞
我建议使用Character类来检查我们正在处理的字符类型:
public static boolean checkPass(String str) {
int normalLower=0;
int normalUpper=0;
int number=0;
int special=0;
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
number++;
} else if (Character.isUpperCase(c)) {
normalUpper++;
} else if (Character.isLowerCase(c)) {
normalLower++;
} else {
special++;
}
}
System.out.println("normalupper " + normalUpper);
System.out.println("normallower " + normalLower);
System.out.println("number" + number);
System.out.println("special " + special);
return normalLower == 0 || normalUpper == 0 || number == 0 || special == 0;
}
TA贡献1798条经验 获得超3个赞
这是使用 Java 8 Streams 和 lambda 函数来获取计数的版本:
public static String getType(int code){
if(Character.isDigit(code)) return "number";
if(Character.isLowerCase(code)) return "normalLower";
if(Character.isUpperCase(code)) return "normalupper";
return "special";
}
public static void checkPass(String s){
Map map =s.chars().mapToObj(x->getType(x))
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println(map);
}
示例运行:
checkPass("密码"); 输出==> {正常上=2,正常下=6}
checkPass("P@ss@Wo1r d3"); 输出==> {特殊=3,数字=2,正常上=2,正常下=5}
添加回答
举报