Mohamed Ifham
Mohamed Ifham

Reputation: 25

count the "IfStmt" statement in java parser

I am using javaparser to parse a java file , when I count the "If" statement it display the output as an incremental number such that Eg: if there are 3 "if" statements then it displays as [ 1 2 3 ]

I want to get only the total number of "IF" statements. eg:[ 3].

I don't want to get all the incrementing count This is my source code.

package org.javaparser.examples.chapter2;

public class VoidVisitorComplete {

private static final String FILE_PATH = "src/main/java/org/javaparser/samples/prime.java";

public static void main(String[] args) throws Exception {

    CompilationUnit cu = StaticJavaParser.parse(new FileInputStream(FILE_PATH));
     

      VoidVisitor<Void> methodNameVisitor = new IfStmtVisitor();
      methodNameVisitor.visit(cu, null);             
}


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++;

            System.out.println( getNumber() );
                  
    }
            
    public int getNumber() {
          
        return i;
    }
       
}
 

}

Upvotes: 0

Views: 429

Answers (1)

Erik McKelvey
Erik McKelvey

Reputation: 1627

You have to put the print statement after all the if statements have been counted.

package org.javaparser.examples.chapter2;

public class VoidVisitorComplete {
    private static final String FILE_PATH = "src/main/java/org/javaparser/samples/prime.java";

    public static void main(String[] args) throws Exception {
        CompilationUnit cu = StaticJavaParser.parse(new FileInputStream(FILE_PATH));
        VoidVisitor<Void> methodNameVisitor = new IfStmtVisitor();
        methodNameVisitor.visit(cu, null);
        System.out.println(methodNameVisitor.getNumber());            
    }
}

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++;
    }
        
    public int getNumber() {
        return i;
    }
}

Upvotes: 1

Related Questions