**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;publicclassCode_18{
publicstaticvoidmain(String[] args){
Scanner input =newScanner(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");}publicstaticbooleanpasswordTestLength(String str){
if(str.length()>=8)returntrue;elsereturnfalse;}publicstaticbooleanpasswordTestLetterOrDigit(String str){
for(int i =0;i < str.length();i++){
if(!Character.isLetterOrDigit(str.charAt(i)))returnfalse;}returntrue;}publicstaticbooleanpasswordTestNumber(String str){
int number =0;for(int i =0;i < str.length();i++){
if(Character.isDigit(str.charAt(i)))
number++;}if(number >=2)returntrue;returnfalse;}}
结果显示:
Enter a string: jxh1025
Invalid Password
Process finished with exit code 0