HJ20 密码验证合格程序(java)(代码解释超清晰)

Hello World(你好,世界!)

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String str = sc.nextLine().replaceAll(" ", "");

            // 1.长度超过8位
            if (str.length() < 8) {
                System.out.println("NG");
                continue;
            }

            // 2.包括大小写字母.数字.其它符号,以上四种至少三种
            /**
             * count:种数
             * length:用于判断每次replaceAll后长度是否变化,变化,则count++
             */
            int count = 0;
            int length = str.length();
            String temp = str.replaceAll("[a-z]", "");
            if (temp.length() < length) {
                count++;
                length = temp.length();
            }
            temp = temp.replaceAll("[A-Z]", "");
            if (temp.length() < length) {
                count++;
                length = temp.length();
            }
            temp = temp.replaceAll("[0-9]", "");
            if (temp.length() < length) {
                count++;
            }
            // 说明有非 大小写字母、数字 的字符
            if (temp.length() > 0) {
                count++;
            }

            if (count < 3) {
                System.out.println("NG");
                continue;
            }

            // 3.判断是否有重复的3个字符
            // 要求是不能超过2个,所以这里直接判断3个即可

            boolean flag = false;

            for (int i = 0; i < str.length() - 2; i++) {
                String t = str.substring(i, i + 3);

                String tt = str.substring(i + 3);

                if (tt.contains(t)) {
                    flag = true;
                    break;
                }
            }
            System.out.println(flag ? "NG" : "OK");
        }
    }