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)

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

s7-1-data-1.txt

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
What your program must print for s7-1-data-1.txt
level: complexity 5 (simple)
greet: complexity 1 (simple)
Most complex: level (5)

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < s7-1-data-1.txt

Windows PowerShell does not understand <:

Get-Content s7-1-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

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.