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}
添加回答
舉報