Q:

Counting the number of if and else excluding the nested if-else

Can anyone tell me how can i write a program where i have to read a c program from a text file and then count the number of if-else statements, excluding the nested if-else.
Here in this program i have counted the number of if and else from a text file, but how do i exlude the nested if from this count?
please help me with it.
package softwaretesting;

import java.io.*;
import java.util.Scanner;

public class SoftwareTesting {

public static void main(String[] args) throws IOException {
    int countIf = 0, countElse = 0;

    Scanner input;
    input = new Scanner(System.in);
    String fileName;
    System.out.println("Enter the path of the file from which no of if and else statements are to be counted");

    fileName = input.next();

    Scanner file;
    file = new Scanner(new File(fileName));

    int count=0;
    while (file.hasNextLine())
    {
        String line = file.nextLine();
        if (line.indexOf("if") != -1 && count%2==0 )
        {   
            countIf++;
        }

        if (line.indexOf("else") != -1  )
        {
            countElse++;
        }

    }

    {
        System.out.println("No of If statements: " + countIf);
        System.out.println("No of Else statements: " + countElse);
    }
}
}

A:

In general counting if-else statements the way you've specified is wrong 'cause in a programming language if-else statement is not only line containing if or else (consider 'if' or 'else' words in comments and so on). It's exactly a statement in a language defined by a specific set of rules - grammar. Moreover your code will return successfully from not even a C program, which might not be correct...
So the ultimate way to solve the problem is to build an AST tree for the input program and traverse it counting only top-level if-else statements.
There are several tools that can help you with this.

ANTLR
JavaCC

Both of them can generate language parsers from the specified grammar. You can use these parsers to figure out what you input program consist of.
The main problem of such approach is finding (creating?) the correct grammar. For example there are lots of grammars for both ANTLR (https://github.com/antlr/grammars-v4) and JavaCC (https://java.net/projects/javacc/downloads/directory/contrib/grammars); but none of them can be used to generate AST - only plain parsing will be produced. On the other hand since you need to count only if-else statements you might be good with parsing only (without AST tree)...
So at this point there are 2 possible solutions:

Manually update generated by ANTLR/JavaCC parser to count if-else statements.
Find/create a C grammar for ANTLR/JavaCC to produce AST of the input program and traverse it in search for a top-level if-else statements.

ps: for more info on updating grammars to support AST trees see How to implement JJTree on grammar (JavaCC) and How to output the AST built using ANTLR? (ANTLR).

