0

Need to calculate the number of if-else clauses. I'm using java parser to do it.

What I've done till now: I've obtained the count of all if and else-if clauses by using the function

node.getChildNodesByType(IfStmt.class))

Problem: How do I count the else clauses? This function ignores the "else" clause.

Example:

if(condition)
{ 
     if(condition 2)
       //
     else
 }

 else if(condition 3)
{
     if (condition 4) 
      // 
     else
}
 else
{
   if(condition 5) 
      // 
}

In this case, I'd want the answer to be 8 but the size of the call will return 5 because it encounters only 5 "if's" and ignores the else clauses. Is there any function that can directly help me count the else clauses?

My code:

  public void visit(IfStmt n, Void arg) 
            {
            System.out.println("Found an if statement @ " + n.getBegin());
            }

            void process(Node node)
            {
                count=0;
                for (Node child : node.getChildNodesByType(IfStmt.class))
                {
                    count++;
                   visit((IfStmt)child,null);   
                }
            }
xmacz
  • 394
  • 1
  • 5
  • 14
  • See if this helps : https://stackoverflow.com/questions/17552443/google-javaparser-ifstmt-not-counting-consequent-else-if – Arnaud Jun 02 '17 at 09:33
  • @Berger I did go through that. The problem arising is that it does not account for nested if-else. OP's example in that question is different from mine and that answer does not work with this :/ – xmacz Jun 02 '17 at 09:38

1 Answers1

0

This answer has been solved on the following github thread. The in-built methods of the java parser are more than sufficient to help out.

Answer:

 static int process(Node node) {
    int complexity = 0;
    for (IfStmt ifStmt : node.getChildNodesByType(IfStmt.class)) {
        // We found an "if" - cool, add one.
        complexity++;
        printLine(ifStmt);
        if (ifStmt.getElseStmt().isPresent()) {
            // This "if" has an "else"
            Statement elseStmt = ifStmt.getElseStmt().get();
            if (elseStmt instanceof IfStmt) {
                // it's an "else-if". We already count that by counting the "if" above.
            } else {
                // it's an "else-something". Add it.
                complexity++;
                printLine(elseStmt);
            }
        }
    }
    return complexity;
}
xmacz
  • 394
  • 1
  • 5
  • 14