Google javaparser IfStmt不计算后续< else-if> [英] Google javaparser IfStmt not counting consequent <else-if>

查看:485
本文介绍了Google javaparser IfStmt不计算后续< else-if>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google javaparser来解析java文件,当我尝试计算If语句时,似乎我无法获得else-if语句的数量。

I am using Google javaparser to parse the java file, when I try to count the "If" statement, it seems like I can not get the number of "else-if" statement.

例如,我想解析以下代码:

For example, I want to parse the following code:

    if(i>1){
      i++;
    }else if(i>2){
      i++;
    }else if(i>3){
      i++;
    }else{
      i++;
    }

我想获得Cyclomatic的复杂性,以便我需要计算数量if和else-if。
当我使用访客模式时,我只能访问API中定义的IfStmt,代码如下:

I want to get the Cyclomatic complexity so that I need to count the number of "if" and "else-if". When I use Visitor pattern, I can only visit the "IfStmt" defined in the API, the code looks like:

    private static class IfStmtVisitor extends VoidVisitorAdapter<Void> {
    int i = 0;

    @Override
    public void visit(IfStmt n, Void arg) {
        //visit a if statement, add 1
        i++;
        if (n.getElseStmt() != null) {
            i++;
        }
    }

    public int getNumber() {
        return i;
    }
}

无法获得else-if但是带有IfStmt的访问者模式将整个代码块视为一个ifStatement.So,我希望该数字为4,但它是2。

There is no way to get "else-if" but the Visitor pattern with "IfStmt" treats the whole code block as one "if" Statement.So, I expect the number to be 4, but it is 2.

任何人都有一些想法?

推荐答案

if语句只包含一个then Statement和一个else Statement。 else语句可以是隐藏的if语句。所以有一个递归。为了跟踪您所需的复杂性,以下递归方法可能有所帮助:

A if-statement only contains one "then Statement" and one "else Statement". The else Statement can be a hidden if statement. So there is a recursivity. To track your needed complexity the following recursive method may help:

private static class IfStmtVisitor extends VoidVisitorAdapter<Void> {
    int i = 0;

    @Override
    public void visit(IfStmt n, Void arg) 
    {
        cyclomaticCount(n);
    }

    private void cyclomaticCount(IfStmt n)
    {
        // one for the if-then
        i++;
        Statement elseStmt = n.getElseStmt();
        if (elseStmt != null)
        {
            if (  IfStmt.class.isAssignableFrom(elseStmt.getClass())) 
            {
                cyclomaticCount((IfStmt) elseStmt);
            }
            else
            {
                // another for the else
                i++;
            }
        }
    }

    public int getNumber() {
        return i;
    }
}

希望有所帮助。

这篇关于Google javaparser IfStmt不计算后续&lt; else-if&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆