vendredi 2 juin 2017

Calculate total number of if-else clauses(including nested)

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);   
                }
            }

Aucun commentaire:

Enregistrer un commentaire