【习题描述】
(检测密码)一些网站对于密码具有一些规则。编写一个方法,检测字符串是否是一个有效密码。 假定密码规则如下:
• 密码必须至少 8 位字符。
• 密码仅能包含字母和数字。
• 密码必须包含至少两个数字。 编写一个程序,提示用户输入一个密码,如果符合规则,则显示 Valid Password, 否则 显示 Invalid Password。
运行示例如下:
示例1:
输入:2qwerasdf
输出:Invalid Password
示例2:
输入:12abcdefg
输出:Valid Password
public class Exercise6_18 {
public static void main(String[] args) {
// Prompt the user to enter a password
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter a string for password: ");
String s = input.nextLine();
if (isValidPassword(s)) {
System.out.println("Valid Password");
}
else {
System.out.println("Invalid Password");
}
}
/** Check if a string is a valid password */
public static boolean isValidPassword(String s) {
boolean a=true;
for(int i=0; ichar c=s.charAt(i);
if((c>='0'&&c<='9')||(c<='Z'&&c>='A')||(c>='a'&&c<='z')) {
}else a=false;
}
int count=0;
for(int i=0; ichar c=s.charAt(i);
if(c>='0'&&c<='9') count++;
}
if(count>=2) a=true;
else a=false;
if(s.length()<=8) a=false;
return a;
}
}
为什么不用正则表达式呢?一行代码就搞定了