Reputation: 43
I want to count the used control structures (IF - statmens, switch case,..) in a simple Java class and simply save the amount in a variable.
Do you guys have an idea how I can do that?
Upvotes: 2
Views: 227
Reputation: 17454
If I interpreted your question correctly, this is about pattern reading from a text file.
If you just want to have a program to check on another piece of code, you can read the .java as were to read a text file.
As you encounter words like if
or switch
add one to your variable.
Of course, you would want to ensure you are not reading in the commented lines
(I.e. ignore those after //
and not within /* */
)
So how do you do that?
You can read in the lines of code as a String
, make use of String methods like contains
or even make use of regex in Java to check whether that string contains the word you look for.
You can also take note of characters like ;
to help determine the end of a statement in the code.
Upvotes: 1
Reputation: 4274
In general, the information about your source structure will not be preserved in your runtime class. The compiler may change it around, optimize it, add to it, etc, etc.
If you really mean lexical analysis of the source file, and not the class, there are a few packages available to help you do that - but you have to pass the source into them, and the results will not (up to O() notation) reflect the runtime values of these counts.
Upvotes: 0