第六章第十八题(检测密码)(Check password)

第六章第十八题(检测密码)(Check password)

  • **6.18(检测密码)一些网站对于密码具有一些规则。编写一个方法,检测字符串是否是一个有效密码。假定密码规则如下:
    密码必须至少8位字符。
    密码仅能包含字母和数字。
    密码必须包含至少两个数字。
    编写一个程序,提示用户输入一个密码,如果符合规则,则显示Valid Password,否则显示Invalid Password。
    **6.18(Check password) Some websites impose certain rules for passwords. Write a method that checks whether a string is a valid password. Suppose the password rules are as follows:
    A password must have at least eight characters.
    A password consists of only letters and digits.
    A password must contain at least two digits.
    Write a program that prompts the user to enter a password and displays Valid Password if the rules are followed or Invalid Password otherwise.
  • 参考代码:
package chapter06;

import java.util.Scanner;

public class Code_18 {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = input.nextLine();
        if (passwordTestLength(str) && passwordTestLetterOrDigit(str) && passwordTestNumber(str))
            System.out.println("Valid Password");
        else
            System.out.println("Invalid Password");
    }
    public static boolean passwordTestLength(String str){
    
    
        if (str.length() >= 8)
            return true;
        else return false;
    }
    public static boolean passwordTestLetterOrDigit(String str){
    
    
        for (int i = 0;i < str.length();i++){
    
    
            if (!Character.isLetterOrDigit(str.charAt(i)))
                return false;
        }
        return true;
    }
    public static boolean passwordTestNumber(String str){
    
    
        int number = 0;
        for (int i = 0;i < str.length();i++){
    
    
            if (Character.isDigit(str.charAt(i)))
                number++;
        }
        if (number >= 2)
            return true;
        return false;
    }
}

  • 结果显示:
Enter a string: jxh1025
Invalid Password

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/jxh1025_/article/details/109165698