0

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

到目前为止我所做的:我已经通过使用函数获得了所有 if 和 else-if 子句的计数

node.getChildNodesByType(IfStmt.class))

问题: 如何计算 else 子句?此函数忽略“else”子句。

例子:

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

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

在这种情况下,我希望答案为 8,但调用的大小将返回 5,因为它只遇到 5 个“if”并忽略 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);   
                }
            }
4

1 回答 1

0

此答案已在以下 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;
}
于 2017-07-07T08:54:46.943 回答