计算if-else子句的总数(包括嵌套)
问题描述:
需要计算if-else子句的数量。我使用java解析器来做到这一点。计算if-else子句的总数(包括嵌套)
我做了什么至今:通过使用功能 我获得的所有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的“如果”,而忽略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);
}
}
答
这个答案已经以下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;
}
看看这有助于:https://*.com/questions/17552443/google-javaparser-ifstmt-not-counting-consequent-else-if – Berger
@Berger我确实经历了这一点。出现的问题是它没有考虑嵌套的if-else。 OP在该问题中的示例与我的不同,并且该答案不适用于此:/ – xmacz