Start learning free

LESSON 196 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V2 in Scala: Length and Digit Check

Practice Read the full explanation

Extend the length check with a second rule: the password must also contain at least one digit.

You start with:

val 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 as false and becomes true when a digit is seen.
  • Print "Has digit: " 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 hasDigit is true, print Strong; otherwise print Weak.

Try other passwords: with abcdefgh the output is

Length: 8
Has digit: False
Weak

c.isDigit tests a single char. Use (if (hasDigit) "True" else "False") to print a capitalised True/False.

val password = "Secret99"

val length = password.length
println("Length: " + length)
var hasDigit = false
for (c <- password) {
    if (c.isDigit) {
        hasDigit = true
    }
}
println("Has digit: " + (if (hasDigit) "True" else "False"))
if (length >= 8 && hasDigit) {
    println("Strong")
} else {
    println("Weak")
}

STEP 1 OF 8
    Ctrl + Enter to check

    SCALA · PROJECTS: EVERYDAY PROGRAMS

    Password Strength V2 in Scala, explained

    Problem overview

    The checker gets a second rule. A strong password must now have at least 8 characters and also contain at least one digit. The program starts with val password = "Secret99" and prints three lines: the length, whether a digit was found, and the verdict, Strong or Weak.

    For Secret99 the output is:

    Length: 8
    Has digit: True
    Strong

    The flag line must read True or False with a capital letter, as in the example. For abcdefgh the output is Length: 8, Has digit: False and Weak.

    Approach: a flag set by a loop

    The length is one lookup, but "contains a digit" needs a look at every character. The standard pattern is a boolean flag. It starts as false, meaning no digit has been seen yet, and a loop over the characters turns it to true when it meets a digit. After the loop, the flag answers the question for the whole string.

    The flag is only ever switched one way. Once a digit has been found, later characters must not switch it back, so the loop has no else branch: it either sets the flag or does nothing.

    The verdict combines both rules with "and": the password is Strong only if the length is at least 8 and the flag is true. Everything else, whether too short, digit-free or both, is Weak.

    Step by step

    1. Store the length in val length.
    2. Print the first line, Length: followed by the number.
    3. Create the flag. var hasDigit = false is a var, because it changes when a digit is found.
    4. Loop over the characters with for (c <- password). The arrow <- reads as "taken from", and each pass gives c the next character.
    5. Test each character with c.isDigit and set hasDigit to true inside the if.
    6. After the loop, print the flag line. The flag is turned into True or False with an if that gives a value.
    7. Write the verdict if with length >= 8 && hasDigit, printing Strong.
    8. Add the else branch, which prints Weak.

    The solution in Scala

            val password = "Secret99"
    
            val length = password.length
            println("Length: " + length)
            var hasDigit = false
            for (c <- password) {
                if (c.isDigit) {
                    hasDigit = true
                }
            }
            println("Has digit: " + (if (hasDigit) "True" else "False"))
            if (length >= 8 && hasDigit) {
                println("Strong")
            } else {
                println("Weak")
            }

    Details worth knowing:

    • A string is a sequence of characters. for (c <- password) loops over a String directly, and c is a Char. No index is needed.
    • c.isDigit is true for decimal digits. It also accepts digits from other scripts, so the Arabic-Indic digit three, '\u0663', counts as a digit too. For the passwords in this lesson that makes no difference.
    • Booleans print in lowercase. println("Has digit: " + hasDigit) would print Has digit: true. The lesson needs a capital, so it picks the text itself.
    • if is an expression. (if (hasDigit) "True" else "False") has a value: the first string when the flag is true and the second when it is false. The parentheses keep the whole if/else together as one operand of the +.
    • && is "and". It is true only when both sides are, and it skips the right side when the left is already false.

    Following the loop

    For Secret99 the flag stays false while the loop passes S, e, c, r, e and t, because none of them is a digit. At the first 9 the condition is true and the flag becomes true. The second 9 sets it to true again, which changes nothing. The loop always visits all eight characters, even after the flag is set, because this version does not stop early.

    A shorter way to ask the same question

    Scala strings also have an exists method that takes a test and answers whether any character passes it. "Secret99".exists(_.isDigit) gives true and "abcdefgh".exists(_.isDigit) gives false. It does the same job as the loop and the flag in one expression. This lesson builds the flag by hand because the loop-and-flag pattern is the general tool: it works for any test you can write on one character.

    Complexity

    The loop makes one pass over the n characters and does constant work on each, so the time is O(n). The program stores a few values, whatever the password length, so the extra space is O(1). Asking for the length is constant time, so the length check adds nothing to the cost.

    Edge cases and common mistakes

    • Digits only. 12345678 has 8 characters and a digit, so it is Strong under these two rules. Under this lesson's rules, only the length and the digit matter.
    • Long but no digit. abcdefgh prints Has digit: False and Weak.
    • A digit but short. short1 prints Length: 6, Has digit: True and Weak. The flag line reports the digit, and the verdict still fails on length.
    • Resetting the flag. Adding an else { hasDigit = false } inside the loop makes the flag reflect only the last character. Leave the flag alone when the character is not a digit.
    • Using val for the flag. The compiler rejects the assignment in the loop, since a val cannot be reassigned.
    • Printing the flag inside the loop. That prints one line per character instead of one line in total.

    Testing

    PasswordOutput
    Secret99Length: 8, Has digit: True, Strong
    abcdefghLength: 8, Has digit: False, Weak
    12345678Length: 8, Has digit: True, Strong
    short1Length: 6, Has digit: True, Weak
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free