【发布时间】:2017-02-24 21:31:22
【问题描述】:
这是来自 Liang 的 Java Book。基本上,我必须用一种方法检查某个单词是否可以用作密码。
/*
(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.
*/
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("This program checks if the password prompted is valid, enter a password:");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
if (isValidPassword(password))
System.out.println("The password is valid.");
else
System.out.println("The password is not valid.");
public static boolean isValidPassword (String password) {
if (password.length() >= 8) {
// if (regex to include only alphanumeric characters?
// if "password" contains at least two digits...
return true;
}
另外,如果(不需要)我会显示确切的错误类型怎么办?例如,如果我要通知用户只发生了一种错误(例如“您的密码长度正常,但密码中没有数字”)?
【问题讨论】:
-
为什么投反对票?