
正文
《Java语言程序设计》编程练习6.18(检测密码)
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
6.18 (检测密码)一些网站对于密码具有一些规则。编写一个方法,检测字符串是否是一个有效密码。
假定密码规则如下:
• 密码必须至少8位字符。
• 密码仅能包含字母和数字。
• 密码必须包含至少两个数字。
编写一个程序,提示用户输入一个密码,如果符合规则,则显示Valid Password,否则显示Invalid Password。
/** fileName: passwdRule.java
function: 检测输入的密码是否符合密码规则
create Time:2019/10/17
mail: xuangliang1@live.com
*/ import java.util.Scanner;
public class passwdRule{
public static void main(String[] args){ Scanner input = new Scanner(System.in);
System.out.print("请输入密码:");
String passwd = input.next(); //密码检测
if(passwdDigit(passwd)){
if((getPasswdNumber(passwd) >= 2) && ((getPasswdNumber(passwd)+getPasswdDigitNumber(passwd)) == passwd.length())){
System.out.println("Valid Password 通过");
}else
System.out.println("Invalid Password 不通过");
}else{
System.out.println("Invalid Password 不通过");
}
} /** 检测passwd的位数长度是否符合规则, 符合返回true*/
public static boolean passwdDigit(String passwd){
//设置最大字符限制和最小字符限制
final int MAX = 1024;
final int MIN = 8;
int passwdLength = passwd.length();
if((passwdLength >= MIN) && (passwdLength < MAX))
return true;
return false;
} /** 返回passwd中的数字或字母个数 ,k为0表示数字,1表示字母 */
public static int getPasswdDigitNumber(String passwd){
//字母个数
int digitNumber = 0;
char digitUpper;
for(int i = 0; i< passwd.length(); i++){
digitUpper = Character.toUpperCase(passwd.charAt(i));
if(digitUpper > 'A' && digitUpper < 'Z')
digitNumber++;
}
return digitNumber;
} /** 返回passwd的数字个数 */
public static int getPasswdNumber(String passwd){
int number = 0;
int arrayNumber; for(int i = 0; i < passwd.length(); i++){
arrayNumber = passwd.charAt(i);
if((int)arrayNumber > 47 && (int)arrayNumber < 58)
number++;
}
return number;
}
}
这个代码写了1个晚上,删了写,最后发现charAt(i)这个是重点!







