计算 if-else 子句总数(包括嵌套)
Calculate total number of if-else clauses(including nested)
需要计算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,但调用的大小将为 return 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);
}
}
此答案已在以下 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;
}
需要计算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,但调用的大小将为 return 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);
}
}
此答案已在以下 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;
}