首先將問題分解爲可管理的塊。
Password should be at least 8 characters in length.
嗯,這很容易......
if (password.length > 7) {
...
should contain at least one number/digit
Character.isDigit(char)
one capital letter other than the first letter (if the only capital letter is the first letter, that doesn’t pass the complexity test)
Character.isUpperCase(char)
你需要做其他檢查時大寫字符數1
以確定它是否是第一個字符...
if (!Character.isUpperCase(password[0])...
one special character (non-letter; non-digit)
Character.isLetterOrDigit(char)
Spaces are not allowed.
Character.isWhitespace(char)
您需要驗證這一點,因爲這包括製表符,新線路和一堆其他的空格字符
現在,你只需要把邏輯放在一起。
大部分工作的計數字符和檢查,看看,如果你有正確的數字或不
現在,因爲我迂腐,我先來定義核心契約的接口.. 。
public interface PasswordValidator {
public boolean isValid(char[] password);
}
,然後生成一個或多個實現...
public class ComplexPasswordValidator implements PasswordValidator {
@Override
public boolean isValid(char[] password) {
boolean isValid = false;
// At least 8 characters long
if (password.length > 7) {
int digitCount = 0;
int capitalCount = 0;
int nonAlphaDigitCount = 0;
int whiteSpace = 0;
for (char c : password) {
if (Character.isDigit(c)) {
digitCount++;
} else if (Character.isUpperCase(c)) {
capitalCount++;
} else if (Character.isWhitespace(c)) {
// This includes tabs, new lines etc...
whiteSpace++;
} else if (!Character.isLetterOrDigit(c)) {
nonAlphaDigitCount++;
}
}
// Must have a captial character which is not the first character
if (capitalCount > 1 || (capitalCount == 1 && !Character.isUpperCase(password[0]))) {
// Must have a digit, 1 non alpha/digit character and no whitespace
if (digitCount > 0 && nonAlphaDigitCount == 1 && whiteSpace == 0) {
isValid = true;
}
}
}
return isValid;
}
}
現在,這些不拋出任何異常,所以唯一的反饋,你會得到我s true
或false
。如果您需要添加例外情況,那麼您將不會受到影響。
然後,你可以簡單地使用它像...
PasswordValidator pv = new ComplexPasswordValidator();
System.out.println(pv.isValid(new char[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'T', 'e', 's', 't', '_', 'I', 'A', 'm', 'G', 'r', '8'}));
System.out.println(pv.isValid(new char[]{'B', 'a', 'd', '_', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd', '8'}));
System.out.println(pv.isValid(new char[]{'B', 'a', 'd', ' ', 'P', 'a', 's', 's', 'w', 'o', 'r', 'd', '8'}));
你可以設置的歷時的PasswordValidator
實例和方法的順序簡單地傳遞你想
The compiling issue is from the password field....?
任何驗證問題#1 ...
在return
聲明之後放置代碼,這會使代碼不可用
public static boolean checkSSN(String social) {
//...
return valids;
//Code to check password
String password = JOptionPane
.showInputDialog("Please insert a valid password ");
boolean valid = isValid(password);
if (isValid(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
問題#2 ...
Failing to define the parameter type...
public boolean isValid(password) { // What type is password?
請你可以把代碼中的問題本身,而不是鏈接。 –
它說它太長了 – Josh
然後閱讀。 http://stackoverflow.com/help/mcve –