Extend the length check with a second rule: the password must also contain at least one digit.
You start with:
String password = "Secret99";
Build:
Length: 8 Has digit: True Strong
Rules:
- Print
"Length: "followed by the number of characters. - Loop through each character to set a boolean flag
hasDigit, which starts asfalseand becomestruewhen a digit is seen. - Print
"Has digit: "followed by the flag. Write it asTrueorFalsewith a capital letter, exactly as in the example (your language's own boolean prints differently, so choose the text yourself). - If the length is at least 8 and
hasDigitistrue, printStrong; otherwise printWeak.
Try other passwords: with abcdefgh the output is
Length: 8 Has digit: False Weak
Character.isDigit(c) tests a single char. Use (hasDigit ? "True" : "False") to print a capitalised True/False.
String password = "Secret99";
int length = password.length();
System.out.println("Length: " + length);
boolean hasDigit = false;
for (char c : password.toCharArray()) {
if (Character.isDigit(c)) {
hasDigit = true;
}
}
System.out.println("Has digit: " + (hasDigit ? "True" : "False"));
if (length >= 8 && hasDigit) {
System.out.println("Strong");
} else {
System.out.println("Weak");
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
