import java.util.Scanner;

public class Password { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);

    System.out.print("请输入密码:");
    String password = scanner.nextLine();

    if (checkPassword(password)) {
        System.out.println("密码有效");
    } else {
        System.out.println("密码无效");
    }
}

// 检查密码是否只包含字母和数字,并且至少有2个数字
public static boolean checkPassword(String password) {
    boolean hasLetter = false;
    boolean hasDigit = false;
    int digitCount = 0;

    if (password.length() < 8) {
        return false;
    }

    for (int i = 0; i < password.length(); i++) {
        char c = password.charAt(i);

        if (Character.isLetter(c)) {
            hasLetter = true;
        } else if (Character.isDigit(c)) {
            hasDigit = true;
            digitCount++;
        } else {
            return false;
        }
    }

    return hasLetter && hasDigit && digitCount >= 2;
}

}

Java 密码验证代码示例 - 至少包含两个数字

原文地址: https://www.cveoy.top/t/topic/oKY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录