檢測字符串是否是一個有效密碼

要求:
密碼必須至少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;
    }
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章