我試圖用正則表達式做一個密碼,我不明白爲什麼我的代碼不工作:密碼在Java中,通過使用正則表達式的
import java.util.Scanner;
class test {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a password please.");
String password = scanner.nextLine();
int x;
String redex = "(^[0-9]+$)";
String redexx = "(^[A-Z]+$)";
boolean hasSpace = false;
boolean hasUpperCase = false;
boolean hasLetter = false;
boolean hasDigit = false; // we set four booleans to be able to bring up individual error messages.
if (password.length() > 8){
hasLetter = true;
} else {
System.out.println("Your password needs to be at least 8 characters long.");
if (password.matches(redexx)) { // we check to see if the password has at least an upper case letter, one or more digits and a space using regular expressions
hasUpperCase = true;
} if (password.matches(redexx)) {
hasDigit = true;
} if (password.indexOf(' ') == 1) {
hasSpace = true; }
} if (hasLetter && hasDigit && hasUpperCase && !hasSpace) {
System.out.println("Your password is strong.");
} if (!hasDigit) {
System.out.println("You need to put numbers in your password.");
} if (!hasUpperCase) {
System.out.println("You need to use an upper case letter in your password.");
} if (hasSpace) {
System.out.println("You need to delete any spaces in your password.");
} // if we use if statements (and not any "else" or "else if", we get to show all the possible error messages.
}
}
糾正「正則表達式」後「regexx」和編譯後,當我輸入一個完全適用的密碼,它仍然會提示密碼需要一個大寫,它也需要一個數字
你的意思是正則表達式? – procrastinator
你明白爲什麼這些行不能編譯? String redex =(^ [0-9] + $); String redexx =(^ [A-Z] + $); – Stultuske
'password.length()> 8'表示密碼必須至少有9個字符才能通過該測試,而不是8個,因爲您之後寫入3行。 –