PIPI:1002: 安全密码(Java)
2021-01-15 本文已影响0人
天降小纸箱
题目描述: 1002: 安全密码
网络上各类交易活动越来越普及,为了能够安安心心地上网,经常需要设置一个安全的密码。一般来说一个比较安全的密码至少应该满足下面两个条件:
(1)密码长度大于等于8。
(2)密码中的字符应该来自下面“字符类别”中四组中的至少三组。
这四个字符类别分别为:
(1)大写字母:A,B,C...Z;
(2)小写字母:a,b,c...z;
(3)数字:0,1,2...9;
(4)特殊符号:~,!,@,#,$,%,^;
给你一个密码,你的任务就是判断它是不是一个安全的密码。

实现思路:依次判断每个字符的类型
实现代码
public class SecurityPassword {
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
while (inScanner.hasNext()) {
String passwordString = inScanner.nextLine();
if (isSecurity(passwordString)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
public static boolean isSecurity(String password) {
if (password.length() < 8) return false;
int upLetter = 0, lowLetter = 0, digit = 0, specialLetter = 0; // 大写字母,小写字母,数字,特殊字符
for (int i = 0; i < password.length(); i++) {
if (Character.isDigit(password.charAt(i))) {
digit++;
} else if (password.charAt(i) >= 'A' && password.charAt(i) <= 'Z') {
upLetter++; // 大写字母
} else if (password.charAt(i) >= 'a' && password.charAt(i) <= 'z') {
lowLetter++;
} else {
specialLetter++;
}
}
int security = 0;
if (digit > 0) security++;
if (lowLetter > 0) security++;
if (upLetter > 0) security++;
if (specialLetter > 0) security++;
return security > 2;
}
}