I tried to make method which will finding all if conditions in .java file (I assume that file contain only correct if instructions). It should count all "if", but not that which are sorrounded with comments or treaded as string. I tried to solve this problem with StringTokenizer, but I don't know how elided line after "//" sign and strings sorrounded with " ".Is it possible to realize this problem in this way, at all?
public int getIfCount()
{
int counter = 0;
String t = "";
try
{
FileReader file = new FileReader(path);
StringBuffer sb = new StringBuffer();
int tmp;
while ((tmp = file.read()) != -1)
{
sb.append((char)tmp);
}
t = sb.toString();
StringTokenizer stk = new StringTokenizer(t);
String token;
while (stk.hasMoreTokens())
{
token = stk.nextToken();
if (token.contains("/*"))
{
while (stk.hasMoreTokens())
{
if (stk.nextToken().contains("*/"))
break;
}
}
else if (token.contains("//"))
{
while (stk.hasMoreTokens() && stk.nextToken() != "\n")
{
if (stk.nextToken().endsWith("\n"))
break;
}
}
else if (token.contains("\""))
{
if (!token.endsWith("\""))
while (stk.hasMoreTokens())
{
if(stk.nextToken().contains("\""))
break;
}
}
else if (token.startsWith("if"))
counter++;
}
}
catch (FileNotFoundException e)
{
System.out.println("This file does not exist!");
}
catch (IOException e)
{
System.out.println("ERROR");
}
return counter;
}