admin管理员组文章数量:1558091
第六章第十八题(检测密码)(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
版权声明:本文标题:第六章第十八题(检测密码)(Check password) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1727341886a1109514.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论