2017-06-02 101 views
0

需要計算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); 
       } 
      } 
+0

看看這有助於:https://stackoverflow.com/questions/17552443/google-javaparser-ifstmt-not-counting-consequent-else-if – Berger

+0

@Berger我確實經歷了這一點。出現的問題是它沒有考慮嵌套的if-else。 OP在該問題中的示例與我的不同,並且該答案不適用於此:/ – xmacz

回答

0

這個答案已經以下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; 
}