user628083
user628083

Reputation: 353

How to find nested conditons count in java

I have to read java file by java code and to determine the greatest nested count of if statements in it.

for example:

if (someCondition)
{
  if (someCondition)
     {
      // Expression
     }
}

In this case program should display greatest nested if depth is 2.

Now the problem is that position of curly brace after if is uncertain.

for example it can be like :

Curly brace start and end comes in same line
if (someCondition){}

OR
Curly brace start in next line
if (someCondition)
{
}

OR
Conditions without curly brace
if (someCondition)
   if (someCondition) // Single line without curly brace

Can anybody suggest what will be the best way to get the required nested count?

Upvotes: 0

Views: 370

Answers (3)

allingeek
allingeek

Reputation: 1388

I82Much's answer will certainly get you there, but feels a little like cheating.

Knowing little about your project, I would think that a simple stack mechanism with a max value record would do the trick push on { and pop on }. Once you have that basic model working, simply add the special case of control statements with one line bodies (this is valid for if, for, while ...). In those cases, you'll be looking for those keywords, followed by ( and a ). Once you've encountered that combination, if the scan encounters either another control statement or a semi-colon before it encounters a { then this is one of those special cases and you should push (using a special marker indicating to pop on ; rather than }).

Upvotes: 0

Frank
Frank

Reputation: 10571

As the answer already said, you should rely on the AST rather than viewing code manually for this. The AST will never be wrong, your own reading abilities most often will.

I don't know a complete solution right now, but I suggest you spend some time looking at existing tools for computing software metrics. Nesting depth is a typical metric and there should be tools around.

If you can't find anything, you can at least fall back to writing something like an Eclipse plugin. In that case, you could simply load the Java file in the Eclipse editor, and Eclipse performs all the hard work for you and gives you the AST for free. Determining the nesting depth of a given AST is then rendered a simple task. Developing a prototype for that shouldn't take more than a few hours. And it's easy to extend it to cover your whole project and have it answer questions like "which java file in our project has the maximum nesting depth and what depth is that?". But then again.. someone else will surely point out an existing tool that already does this and much more.

Upvotes: 1

I82Much
I82Much

Reputation: 27326

You'll need to parse the Abstract Syntax Tree (AST) of the Java source code. See Java library for code analysis. Once you have the AST, you can do a search to find the longest path of nested conditionals.

Upvotes: 1

Related Questions