【发布时间】: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);
}
}
【问题讨论】:
-
@Berger 我确实经历过。出现的问题是它没有考虑嵌套的 if-else。 OP 在该问题中的示例与我的不同,并且该答案不适用于此:/
标签: java parsing if-statement javaparser