第一个功能:密码有效性检查
实现要求:
Must be between 8 and 15 characters in length
May not contain spaces
Must contain at least one nonnumeric uppercase character and one nonnumeric lowercase character
Must contain at least one numeric digit
目录
初级代码
改进代码
代码实现
- 第一次实现
缺点:代码可读性差,代码大量冗余……
public static boolean Inspect(String password) {
int just = 0;//用来判断密码最后是否有效
int length = password.length();
//长度判断
if(length>8&&length<15) {
// System.out.println("密码长度符合规定。");
just++;
}else if(length<8) {
System.out.println("密码长度太短了");
just--;
}else {
System.out.println("密码长度太长了");
just--;
}
//空格检查
int flag =0;
for(int j = 0;j<length;j++) {
if(password.charAt(j)==' ') {
flag = 1;
break;
}
}
if(flag == 0) {
just++;
}else {
just--;
System.out.println("包含有空格不满足要求");
}
//至少包含一个非数字的大写和小写
int count1 = 0;
int count2 = 0;
for(int j = 0;j<length;j++) {
if(password.charAt(j)>='a'&&password.charAt(j)<='z') {
count1++;
}
if(password.charAt(j)>='A'&&password.charAt(j)<='Z') {
count2++;
}
}
if(count1>=1&&count2>=1) {
just++;
}else {
just--;
System.out.println("没有包含一个大写字母或小写字母");
}
//至少包含一个数字
int flag1 = 0;
for(int j = 0;j<length;j++) {
if(password.charAt(j)>='0'&&password.charAt(j)<='9') {
flag =1;
}
}
if(flag == 1) {
just++;
}else {
just--;
System.out.println("没有包含一个数字位");
}
//看是密码是否满足要求
if(just==4) {
return true;
}else {
return false;
}
}
学习改进实现代码,第二次实现
public static void main(String[] args) {
boolean isLengthOk = false;
boolean hasSpace = false;
boolean hasUpperCase = false;
boolean hasDigth = false;
boolean hasLowerCase = false;
System.out.println("请输入一个密码:");
Scanner sc = new Scanner(System.in);
String password = sc.nextLine();
int len = password.length();
if (len >= 8 && len <= 15) {
isLengthOk = true;
}
for (int i = 0; i < len; i++) {
char c = password.charAt(i);
if (c == ' ') {
hasSpace = true;
}
if (c >= 'a' && c <= 'z') {
hasLowerCase = true;
}
if (c >= 'A' && c <= 'Z') {
hasUpperCase = true;
}
if (c >= '0' && c <= '9') {
hasDigth = true;
}
}
String info = "";
if (isLengthOk && hasSpace && hasLowerCase && hasUpperCase && hasDigth) {
info = "符合密码要求";
System.out.println("恭喜你的密码" + password + info);
} else {
if (!isLengthOk) {
info += "长度不符合要求\n";
}
if (hasSpace) {
info += "密码包含了空格\n";
}
if (!hasUpperCase) {
info += "密码至少包含一个大写\n";
}
if (!hasLowerCase) {
info += "密码至少包含一个小写\n";
}
if (!hasDigth) {
info += "密码至少需要一个数字\n";
}
}
System.out.println("你的密码无效" + password + "原因如下:");
System.out.println(info);
}
总结:
好的代码是不需要注释的,
提高代码的健壮性,减少重复代码