要求:
密码必须至少8位字符;
密码仅能包含字母和数字;
密码必须包含至少两个数字;
代码:
package com.im;
import java.util.Scanner;
public class Demo618 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("请输入密码,如果成功则显示成功,否则显示失败!:");
String Pwd = input.nextLine(); //输入的密码
isValidPassword(Pwd);
}
public static void isValidPassword(String Pwd){ //判断密码是否有效
if(isThanEightCharacter(Pwd) && isOnlyCharAndNum(Pwd) &&
isThanTwoDigit(Pwd)){
System.out.println("Valid Password!"); //密码有效
}else{
System.out.println("InValid Password!"); //密码无效
}
}
public static boolean isThanEightCharacter(String Pwd){ //判断是否少于8个字符
if(Pwd.length() < 8){
return false;
}else{
return true;
}
}
public static boolean isOnlyCharAndNum(String Pwd){ //判断只能包含字母和数字
for(int i=0; i<Pwd.length(); i++){
if(!Character.isLetter(Pwd.charAt(i)) && //字符串中的i对应字符判断是否是字母
!Character.isDigit(Pwd.charAt(i))){ //字符串中的i对应字符判断是否是数字
return false;
}else{
return true;
}
}
return false;
}
public static boolean isThanTwoDigit(String Pwd){ //判断至少有两个数字
int count = 0; //判断是数字的计数器
for(int i=0; i<Pwd.length(); i++){
if(Character.isDigit(Pwd.charAt(i))){
count++;
}
}
if(count>2){
return true;
}else{
return false;
}
}
}