Start learning free

LESSON 197 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V3 in Scala: Four Character-Class Flags

Practice Read the full explanation

Track four Boolean flags for a password: does it contain an uppercase letter, a lowercase letter, a digit, and a symbol (non-alphanumeric)?

You start with:

val password = "Secret!99"

Build:

Length: 9
Upper: True
Lower: True
Digit: True
Symbol: True
Strong

Rules:

  • Print "Length: " followed by the number of characters.
  • Start four flags (hasUpper, hasLower, hasDigit, hasSymbol) at false. Loop over every character and set the matching flag to true.
  • A symbol is any character that is not a letter and not a digit.
  • Print one line per flag, in this order: "Upper: ", "Lower: ", "Digit: ", "Symbol: ", each followed by the flag. Write it as True or False with 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 all four flags are true (stricter than the last lesson), print Strong; otherwise print Weak.

Try other passwords: with secret99 the output is

Length: 8
Upper: False
Lower: True
Digit: True
Symbol: False
Weak

Use c.isUpper, c.isLower, c.isDigit and c.isLetterOrDigit inside for (c <- password).

val password = "Secret!99"

val length = password.length
println(s"Length: $length")
var hasUpper = false
var hasLower = false
var hasDigit = false
var hasSymbol = false
for (c <- password) {
    if (c.isUpper) {
        hasUpper = true
    }
    if (c.isLower) {
        hasLower = true
    }
    if (c.isDigit) {
        hasDigit = true
    }
    if (!c.isLetterOrDigit) {
        hasSymbol = true
    }
}
println("Upper: " + (if (hasUpper) "True" else "False"))
println("Lower: " + (if (hasLower) "True" else "False"))
println("Digit: " + (if (hasDigit) "True" else "False"))
println("Symbol: " + (if (hasSymbol) "True" else "False"))
if (length >= 8 && hasUpper && hasLower && hasDigit && hasSymbol) {
    println("Strong")
} else {
    println("Weak")
}

STEP 1 OF 13
    Ctrl + Enter to check

    SCALA · PROJECTS: EVERYDAY PROGRAMS

    Password Strength V3 in Scala, explained

    Problem overview

    The checker now asks for variety. A password is Strong only when it is at least 8 characters long and contains an uppercase letter, a lowercase letter, a digit and a symbol. A symbol is any character that is neither a letter nor a digit. The program starts with val password = "Secret!99" and prints the length, one line for each of the four flags, in the order Upper, Lower, Digit, Symbol, and the verdict.

    For Secret!99 the output is:

    Length: 9
    Upper: True
    Lower: True
    Digit: True
    Symbol: True
    Strong

    For secret99 there is no capital and no symbol, so the output is Length: 8, Upper: False, Lower: True, Digit: True, Symbol: False and Weak.

    Approach: one pass, four flags

    The previous version tracked one flag, hasDigit. This one scales the same idea to four: hasUpper, hasLower, hasDigit and hasSymbol, all starting at false. A single loop over the characters tests each character against all four classes, and each test can only switch its own flag to true.

    The four tests are separate if statements, not an if / else if chain. A character belongs to at most one class, so a chain would also give correct answers, but separate tests make each rule independent and readable, and each one can be changed without affecting the others.

    The symbol test is defined by exclusion. Rather than listing symbols, the code asks whether the character is not a letter and not a digit. c.isLetterOrDigit is true for both kinds, so negating it with ! leaves the symbols, including the space.

    Step by step

    1. Store the length in val length.
    2. Print the length line, here with an interpolated string, s"Length: $length".
    3. Create hasUpper and hasLower as vars set to false.
    4. Create hasDigit and hasSymbol the same way.
    5. Start the loop for (c <- password), with its closing brace written right away.
    6. First test: if c.isUpper, set hasUpper to true.
    7. Second test: if c.isLower, set hasLower to true.
    8. Third test: if c.isDigit, set hasDigit to true.
    9. Fourth test: if !c.isLetterOrDigit, set hasSymbol to true.
    10. After the loop, print the four flag lines, in order, each turned into True or False with an if that gives a value.
    11. Write the verdict. Join five conditions with &&: the length and the four flags. Print Strong if all hold, and Weak in the else.

    The solution in Scala

            val password = "Secret!99"
    
            val length = password.length
            println(s"Length: $length")
            var hasUpper = false
            var hasLower = false
            var hasDigit = false
            var hasSymbol = false
            for (c <- password) {
                if (c.isUpper) {
                    hasUpper = true
                }
                if (c.isLower) {
                    hasLower = true
                }
                if (c.isDigit) {
                    hasDigit = true
                }
                if (!c.isLetterOrDigit) {
                    hasSymbol = true
                }
            }
            println("Upper: " + (if (hasUpper) "True" else "False"))
            println("Lower: " + (if (hasLower) "True" else "False"))
            println("Digit: " + (if (hasDigit) "True" else "False"))
            println("Symbol: " + (if (hasSymbol) "True" else "False"))
            if (length >= 8 && hasUpper && hasLower && hasDigit && hasSymbol) {
                println("Strong")
            } else {
                println("Weak")
            }

    Scala details in this solution:

    • String interpolation. The s before the quotes in s"Length: $length" turns on interpolation, so $length is replaced by the variable's value. The other lines use +. Both forms give the same text, and a literal dollar sign in an s string is written $$.
    • isUpper and isLower are methods on Char. Letters from other alphabets count too, so an accented lowercase letter such as é is lowercase.
    • !c.isLetterOrDigit uses ! to flip a Boolean. It applies to the result of the call, so !c.isLetterOrDigit reads as c is not a letter or digit.
    • Booleans print in lowercase. Printing a flag directly would give true, so every flag line picks its text with if (flag) "True" else "False", in parentheses.
    • Repeated shape. The four flag lines differ only in the label and the flag. When code repeats like this it is correct but long, and a small helper function could remove the repetition. The lesson keeps it explicit so that each line can be checked on its own.

    Following the loop

    For Secret!99 the flags change in the order the characters arrive. The first character, S, sets hasUpper. The next, e, sets hasLower. The ! is neither a letter nor a digit, so it sets hasSymbol, and the first 9 sets hasDigit. After that, every flag is already true and the remaining characters change nothing. Since each character reaches all four tests, it does not matter in which order the classes show up in the password.

    Complexity

    The loop visits each of the n characters once and does four constant-time tests per character, so the time is O(n). The program keeps a length and four booleans, so the extra space is O(1).

    Edge cases and common mistakes

    • The space is a symbol. Secret 99 has a space and no punctuation. The space is neither a letter nor a digit, so Symbol: True and the password is Strong.
    • Missing exactly one class. Secret99 has 8 characters, a capital, small letters and digits, but no symbol. The output has Symbol: False and Weak.
    • Using else if between the tests. It works for this data, but then a later test is skipped whenever an earlier one matches, which makes changes to the rules riskier.
    • Treating a symbol as "not a letter". A digit is not a letter either, so the symbol test needs to exclude digits too. Testing only !c.isLetter would mark every digit as a symbol.
    • Forgetting the length. A password of seven characters with all four classes, such as Aa1!xyz, has all four flags but is still Weak.
    • Wrong order of lines. The flag lines must be Upper, Lower, Digit and Symbol, as listed.

    Testing

    PasswordFlags (Upper, Lower, Digit, Symbol)Verdict
    Secret!99True, True, True, TrueStrong
    secret99False, True, True, FalseWeak
    Secret 99True, True, True, TrueStrong
    Secret99True, True, True, FalseWeak
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free