Start learning free

LESSON 167 OF 410 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V4 - Count Character Classes in Java

Practice

Count how many characters of each class the password contains.

You start with:

String password = "Hello!World9";

Build:

Uppercase: 2
Lowercase: 8
Digits: 1
Symbols: 1

Rules:

  • Use four integer counters, all starting at 0.
  • Loop through each character and add 1 to the matching counter.
  • Treat any character that is not a letter and not a digit as a symbol.
  • Print one line per counter, in this order: "Uppercase: ", "Lowercase: ", "Digits: ", "Symbols: ", each followed by the count.

Try other passwords: with Pass word!2 the output is

Uppercase: 1
Lowercase: 7
Digits: 1
Symbols: 2

Character.isUpperCase, isLowerCase, isDigit, isLetterOrDigit, with ++ counters.

String password = "Hello!World9";

int uppercase = 0;
int lowercase = 0;
int digits = 0;
int symbols = 0;
for (char c : password.toCharArray()) {
    if (Character.isUpperCase(c)) {
        uppercase++;
    }
    if (Character.isLowerCase(c)) {
        lowercase++;
    }
    if (Character.isDigit(c)) {
        digits++;
    }
    if (!Character.isLetterOrDigit(c)) {
        symbols++;
    }
}
System.out.println("Uppercase: " + uppercase);
System.out.println("Lowercase: " + lowercase);
System.out.println("Digits: " + digits);
System.out.println("Symbols: " + symbols);

STEP 1 OF 13
    Ctrl + Enter to check

    Password Strength V4 in Java

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free