title: How can i keep track of multiple counter variables
body: <p>I have written some code that count the number of "if" statements from unknown number of files. How can i keep a count for each file separate and a total of "if" from all files?</p>
  
  <p>code:</p>
  
  <pre><code>import java.io.*;
  
  public class ifCounter4 
  {
      public static void main(String[] args) throws IOException
      {
          // variable to keep track of number of if's
          int ifCount = 0;
  
          for (int c = 0; c &lt; args.length; c++)
          {
              // parameter the TA will pass in
              String fileName = args[c];
  
              // create a new BufferReader
              BufferedReader reader = new BufferedReader( new FileReader (fileName));
              String line  = null;
              StringBuilder stringBuilder = new StringBuilder();
              String ls = System.getProperty("line.separator");
  
              // read from the text file
              while (( line = reader.readLine()) != null) 
              {
                  stringBuilder.append(line);
                  stringBuilder.append(ls);
              }
  
              // create a new string with stringBuilder data
              String tempString = stringBuilder.toString();
  
              // create one last string to look for our valid if(s) in
              // with ALL whitespace removed
              String compareString = tempString.replaceAll("\\s","");
  
              // check for valid if(s)
              for (int i = 0; i &lt; compareString.length(); i++)
              {
                  if (compareString.charAt(i) == ';' || compareString.charAt(i) == '}' || compareString.charAt(i) == '{') // added opening "{" for nested ifs :)
                  {
                      i++;
  
                      if (compareString.charAt(i) == 'i')
                      {
                          i++;
  
                          if (compareString.charAt(i) == 'f')
                          {
                              i++;
  
                              if (compareString.charAt(i) == '(')
                                  ifCount++;
                          } // end if
                      } // end if
                  } // end if
  
              } // end for
  
           // print the number of valid "if(s) with a new line after"
           System.out.println(ifCount + " " + args[c]);  // &lt;-- this keeps running total
                                                         // but not count for each file
          }
  
          System.out.println(); 
  
      } // end main
  } // end class 
  </code></pre>