计算if-else子句的总数(包括嵌套)

时间:2017-06-02 09:26:33

标签: java parsing if-statement javaparser

需要计算if-else子句的数量。我正在使用java解析器来完成它。

到目前为止我做了什么: 我通过使用函数

获得了所有if和else-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's”并忽略else子句。是否有任何函数可以直接帮我计算else子句?

我的代码:

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

1 个答案:

答案 0 :(得分:0)

以下github thread上的答案已经已解决。 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;
}