计算IF-ELSE子句的总数(包括嵌套)



需要计算IF-ELSE子句的数量。我正在使用Java解析器来做到这一点。

我到现在所做的:我通过使用函数

获得了所有if和elly-if子句的计数
node.getChildNodesByType(IfStmt.class))

问题:我如何计算其他条款?此函数忽略" else"子句。

示例:

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

在这种情况下,我希望答案是8,但通话的大小将返回5,因为它仅遇到5" if",而忽略了其他条款。是否有任何可以直接帮助我计算其他条款的功能?

我的代码:

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

此答案已在以下github线程上已解决。Java解析器的内置方法足以帮助您。

答案:

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

最新更新