THINK FIRST·CODE LATER

← All labs

Cyclomatic complexity meter

Problem

Estimate McCabe's cyclomatic complexity of Java methods.

Input: several methods. Each method starts with a line METHOD name and ends with a line END. Between them is Java code.

For each method, count the decision points in its code:

  • the keywords if, for, while, case, catch — as whole words (so notify or format do not count, and else if counts once, for its if);
  • the operators &&, || and ? (the ternary operator).

Before counting, remove string literals ("...", no escaped quotes needed) and line comments (everything from // to the end of the line).

Complexity = decisions + 1. Rating: simple (≤ 5), moderate (6–10), complex (11–20), very complex (> 20). Print name: complexity C (rating) for each method, then Most complex: name (C) (first on a tie).

Input:

METHOD level
if (score >= 90 && !late) {
    return 3;
} else if (score >= 60) {
    return 2;
}
return late ? 0 : 1;
END
METHOD greet
System.out.println("if you see this, for sure || nothing"); // if while
END

Output:

level: complexity 5 (simple)
greet: complexity 1 (simple)
Most complex: level (5)

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.