【问题标题】:Calculate total number of if-else clauses(including nested)计算 if-else 子句的总数(包括嵌套)
【发布时间】:2017-06-02 09:26:33
【问题描述】:

需要计算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);   
                }
            }

【问题讨论】:

  • 看看这是否有帮助:stackoverflow.com/questions/17552443/…
  • @Berger 我确实经历过。出现的问题是它没有考虑嵌套的 if-else。 OP 在该问题中的示例与我的不同,并且该答案不适用于此:/

标签: java parsing if-statement javaparser


【解决方案1】:

此答案已在以下 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多