Finding if conditions in .java file

ⅰ亾dé卋堺 提交于 2019-12-12 03:56:41

问题


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

回答1:


No need to implement it yourself. What you are doing is implementing the basics of a parser. Although it is good to have some idea of what is going on when parsing, I suggest using a library such as https://github.com/javaparser/javaparser. Have fun.



来源:https://stackoverflow.com/questions/42608067/finding-if-conditions-in-java-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!