java小程式——檢測密碼
阿新 • • 發佈:2019-01-06
請使用者輸入密碼,並檢測密碼是否有效
有效條件:
- 密碼必須至少八位字元
- 密碼僅能包含字母和數字
密碼必須包含至少兩個數字
小結:正則表示式檢驗字串
package test;
import java.util.Scanner;
public class passwordDetection {
public static void main(String[] args) {
String password = "";
do {
password = getPassword();
}while(rule(password) == false );
}
/*獲取密碼*/
public static String getPassword() {
Scanner input = new Scanner(System.in);
System.out.println("請輸入密碼:");
String password = input.nextLine();
return password;
}
/*檢驗密碼*/
public static boolean rule(String password) {
if(eightWord(password) == false ) {
System.out.println("您輸入的不是八位!");
return false;
}
else if (numberWord(password) == false) {
System.out.println("您輸入的密碼應僅包含數字和字母!");
return false;
}
else if (twoNumber(password) == false) {
System.out.println("密碼應至少兩個數字!" );
return false;
}
else {
System.out.println("密碼合格!");
return true;
}
}
/*檢驗至少八位密碼*/
public static boolean eightWord (String password) {
int len = password.length();
if (len >= 8)
return true;
else
return false;
}
/*檢驗密碼僅能包含字母和數字*/
public static boolean numberWord (String password) {
boolean flag = password.matches("[a-zA-Z0-9]{8,}");
return flag;
}
/*檢驗密碼包含至少兩個數字*/
public static boolean twoNumber (String password) {
char word;
int i = 0,flag = 0;
for(i = 0; i < 8; i++) {
word = password.charAt(i);
if(word < '9' && word > '0')
flag++;
if(flag >= 2)
return true;
}
return false;
}
}