Java檢測密碼

Question:一些網站對於密碼具有一定規則。編寫一個方法,檢測字符串是否是一個有效密碼。

Example:假定密碼規則如下:

密碼必須至少8位字符。

密碼僅能包含字母和數字。

密碼必須包含至少兩個數字。

Answer

(一)第一種方法視通過字符串的方法對給出的密碼字符進行判斷,得到結果

import java.util.Scanner;
public class PassWord {
	public static int NumberCount(String s){//計算字符串中的數字的個數
		int count = 0;
		for(int i = 0;i < s.length();i++){
			if(Character.isDigit(s.charAt(i)))
			count++;
		}
		return count;
	}
	public static boolean Test(String s){//字符串中是否僅含字母和數字
		boolean Password = false;
		for(int i = 0;i<s.length();i++){
			if(Character.isDigit(s.charAt(i))||Character.isLetter(s.charAt(i)))
				Password = true;
			else{
				Password = false;
				break;
			}
		}
		return Password;
	}
	public static void TestString(String s){檢驗是否符合規則
		if(NumberCount(s) >= 2 && s.length() >= 8 && Test(s))
			System.out.println("The password is valid");
		else 
			System.out.println("The password is invalid");
	}
	public static void main(String []args) {//測試程序
		Scanner input  = new Scanner(System.in);
		System.out.println("請輸入密碼:");
		String password = input.nextLine();
		PassWord string = new PassWord();
		string.TestString(password);
	}
	
}



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